今天呢,仍然是简单的介绍几个方法,获取元素对象的尺寸以及元素的位置。在JavaScript中,咱们经过offset/client获取元素在页面中的位置和尺寸,一样在jQuery中,咱们也须要知道如何去获取元素的大小以及元素的偏移量。javascript
获取元素的宽高 —— 内容区的大小html
width() height() java
// 对象的宽高 console.log($("div").width()); // 返回为数字型 console.log($("div").height());
宽高 width + padding动画
innerWidth() innerHeight() spa
// 包括padding值 console.log($("div").innerWidth()); console.log($("div").innerHeight());
宽度为:width + padding + bordercode
outerHeight() outerWidth()htm
// 包括padding和border的值 console.log($("div").outerHeight()); console.log($("div").outerWidth());
宽度:width + padding + border +margin对象
// padding+border+margin console.log($("div").outerHeight(true)); console.log($("div").outerWidth(true));
上面方法的返回值均是数值型,没有单位blog
获取元素的位置有三种方法 offset() position() srcollLeft()/srcollTop()事件
offset():元素距离文档的位置;此方法中有两个属性top和left。能够获取元素的位置同时还能够设置元素的偏移,设置属性值时,须要在方法中传递参数,以对象的形式传递。
// 1. 距离文档的距离 有两个属性 top和left console.log($("div").offset().top); console.log($("div").offset().left); // 若要更改值 能够在offset方法里传对象参数 // $("div").offset({ // top: 300, // left: 100 // });
position() :元素距离有的定位的父级元素的距离,若是没有开启定位的父级元素,则以文档为标准.
注意:这个方法只能获取元素的位置并不能设置。
<style> .parent { position: relative; top: 300px; width: 200px; height: 200px; background-color: saddlebrown; } .son { position: absolute; top: 20px; left: 15px; width: 100px; height: 100px; background-color: slategrey; } </style> <div class="parent"> <div class="son"></div> </div>
// 2. 获取距离设有定位父级位置position 若是没有定位的父级 则以文档为准 // position方法只能获取不能设置 console.log($(".son").position());
srcollLeft()/srcollTop() : 页面滚动时,页面(或者元素)被卷去的头部和左侧距离
$(window).scroll() 页面滚动事件;
$(window).scroll(function () { var top = $(document).scrollTop(); // 页面卷去的头部的距离 // 当页面卷去的头部的距离 = 内容区距离顶部的距离 返回顶部按钮显示 if (top >= $(".box").offset().top) { $(".back").fadeIn(); } else { $(".back").fadeOut(); } })
模拟一下返回顶部的效果:当鼠标滑到内容区域时返回顶部的按钮显示,点击返回顶部按钮能够回到顶部。
详细的在代码的注释里都有哈。
<style> .box { width: 80%; height: 800px; background-color: skyblue; margin: 500px auto 0; } .back { display: none; position: fixed; right: 50px; top: 500px; width: 50px; height: 50px; background-color: pink; } </style> <div class="box">内容区</div> <div class="back">返回顶部</div> <script> $(function(){ $(window).scroll(function () { // console.log(11); var top = $(document).scrollTop(); // 页面卷去的头部的距离 // console.log(top); // 当页面卷去的头部的距离 = 内容区距离顶部的距离 返回顶部按钮显示 if (top >= $(".box").offset().top) { $(".back").fadeIn(); } else { $(".back").fadeOut(); } }) $(".back").on("click", function () { // $(document).scrollTop(0); // 带动画的返回顶部 // 只有元素作动画 切记 不能是文档 而是body和html元素作动画 $("body,html").stop().animate({ scrollTop: 0 }) }) }) </script>
坚持读书的第四天!!!!!