本文通过具体的实例来讲述jquery里prop和attr的区别及使用方法。

在jquery里,我们要获取一个标签元素的属性,可以用attr或者prop,那么两者有什么区别呢?

其实很简单:

attr可以用来获取或生成“直接写在html标签里的属性”

prop可以用来获取元素的JS属性,如scrollHeight,offsetHeight等。

我们知道,scrollHeight是js里用来获取元素的完整高度,它是js的属性,并不是jquery属性,如果要在jquery里使用这个属性的话,需要把jquery对象转换成js对象,这样才能使用js的属性,而另一种方法就是用jquery里的prop函数

一个关于滚动条的实例:

<!doctype html>
<html lang="en">
<head>
<title>jquery操作滚动条的在线演示-aijQuery.cn</title>
<script language="JavaScript" src="http://cdn.bootcss.com/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
</head>
<body style="height:2000px">
<DIV id="aijquery1" class="container-fluid text-center pt-4" style="height:350px">
这是div#aijquery1<br>
<button id="bt1">滚动到div#aijquery2</button>
</DIV>
<DIV id="aijquery2" class="container-fluid text-center pt-4" style="height:200px;overflow:auto;border:2px solid red">
这是div#aijquery2<br><button id="bt2">滚动到div#aijquery1</button>
<div style="height:450px;border:1px solid #green;padding-top:50px">
这是div#aijquery2内的子DIV<br>
<button id="bt3">操作div#aijquery2的滚动条滚动到底端</button>
</div>
这是div#aijquery2的底部
</DIV>
<script language="javascript">
$("#bt1").click(function(){
//$("html,body").scrollTop($("#aijquery2").offset().top);
$("html,body").animate({scrollTop:$("#aijquery2").offset().top},1000);
});
$("#bt2").click(function(){
//$("html,body").scrollTop($("#aijquery1").offset().top);
$("html,body").animate({scrollTop:$("#aijquery1").offset().top},1000);
});
$("#bt3").click(function(){
//$("#aijquery2").scrollTop($("#aijquery2")[0].scrollHeight);
$("#aijquery2").animate({scrollTop:$("#aijquery2").prop("scrollHeight")},500);
});
</script>
</body>
</html>

  

在上面的实例里,我们要操作滚动条滚动到元素的底部时,就需要取得元素的scrollHiehgt属性的值,我们可以直接用"$(div).prop('scrollHeight')"来获取,但如果换成attr就获取不到了。

如果我们深入jquery的源码来研究,就能发现,jquery里的attr是基于setAttributegetAttribute来实现的,所以用attr是获取不到js对象的属性值的;

而prop是通过对象实现的,如document.getElementById('div').name = 'one';

那么,在实际中,我们除了上面的情况外,我们什么时候用attr,什么时候用prop呢?

在我们要操作的是标签元素固有的一些属性时,推荐使用prop,固有属性指的是标签本身就有的一些属性,如a标签的href属性,img标签的src属性;

而在我们要操作的是自定义的一些属性时,推荐用attr;

最新文章

  1. Xcode找不到模拟器
  2. Hello Vagrant
  3. Sticky Footer (让页脚永远停靠在页面底部,而不是根据绝对位置)
  4. NOIP2011普及组 瑞士环 保序性
  5. 【JAVA - SSM】之MyBatis插入数据后获取自增主键
  6. DNS服务器安装配置案例详解
  7. 同一个页面多个CALayer重绘的办法
  8. 经典排序算法 — C#版本(中)
  9. Windows 上编译 corefx 源码生成 Linux 上可用的 System.Data.SqlClient.dll
  10. ID绘图工具的使用5.29
  11. FFmpeg制作+x264+faac
  12. 适配ipad Pro
  13. 运维人员word优化
  14. systemd学习笔记
  15. vue基础——组件基础
  16. C/C++标准有哪些?
  17. vue之slot,组件标签嵌套
  18. 4、Angular2 pipe
  19. Java学习关于集合框架的基础接口--Collection接口
  20. CAD交互绘制文字(com接口)

热门文章

  1. webapi中session为null的解决方案
  2. SoundPool
  3. Delphi开发安卓程序的感受
  4. LWIP
  5. 【OCP-052】052最新考试题库分析整理-第7题
  6. “全栈2019”Java第九十六章:抽象局部内部类详解
  7. jquery中通过添加readonly或者disabled属性实现行为禁止 / 去除某个属性的方法
  8. Struts2、SpringMVC、Servlet(Jsp)性能对比 测试
  9. Linux文件索引节点相关概念
  10. HttpURLConnection发送GET、POST请求