1 尺寸位置操作
1.1 高度和宽度操作(尺寸)
高度操作height()/width() :
作用:设置或获取匹配元素的高度/宽度值(返回number)
width([val|fn])
//带参数表示设置高度
$(selector).height(200);
//不带参数获取高度
$(selector).height();
//带回调函数
$(selector).width(function(i,w){ });
- i - 可选。接受选择器的 index 位置(建议添上)
- w - 可选。接受选择器的当前值。
当给元素设置了固定的w/h后设置padding、border属性不能获取padding、border只能获取设置的w/h;大小由padding撑起,可获得padding的w/h但不能获取border的尺寸
案例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .box{ width: 300px; /*height: 200px;*/ padding: 50px ; background-color: pink; cursor: pointer; text-align: center; border:5px solid hotpink; } </style> </head> <body> <div class="event"> <button class="but">尺寸</button> <div class="box"> <p>https://blog.csdn.net/muzidigbig</p> </div> <p>你既然认准一条道路,何必去打听要走多久。</p> </div> </body> <script src="jquery-3.3.1.js"></script> <script> //不带参获取当前对象的宽高;带参设置对象的宽高 var w = $('.box').width(); var h = $('.box').height(); console.log('w:'+w+' h:'+h); // var sh = $('.box').height(200); $('.but').on('click',function () { //以 10 像素的幅度增加'.box'元素的宽度 $('.box').width(function (i,w) { return w+10; }); }) </script> </html>
css()获取高度和height获取高度的区别?
1.2 坐标值操作(位置)
offset()
作用:获取或设置元素在当前窗口(整个页面)的偏移位置
// 无参数表示获取,返回值为:{left:num,top:num},值是相对于document的位置
$(selector).offset();
// 有参数表示设置,参数推荐使用数值类型
$(selector).offset({left:100, top: 150});
注意点:设置offset后,如果元素没有定位(默认值:static),则被修改为relative
<script> $('.but').on('click',function () { var offset = $('.box').offset({left:200,top:200}); console.log(offset); }) </script>
1.3 position()
作用:获取相对于其最近的具有定位的父元素的位置。
// 获取,返回值为对象:{left:num, top:num}
$(selector).position();
注意:只能获取,不能设置(没有参数)。
1.4 scrollTop()
作用:获取或者设置元素垂直方向滚动的位置(被卷去的高度,必须要有滚动条)
// 无参数表示获取偏移
// 有参数表示设置偏移,参数为数值类型
$(selector).scrollTop(100);
scrollLeft()
作用:获取或者设置元素水平方向滚动的位置
$(selector).scrollLeft(100);
对scrollTop的理解:
垂直滚动条位置是可滚动区域在可视区域上方的被隐藏区域的高度。
如果滚动条在最上方没有滚动或者当前元素没有出现滚动条,那么这个距离为0
<script> $('.but').on('click',function () { //初始状态值 console.log($('.box').scrollTop()); $('.box').scrollTop(30); //获得设置后的值 console.log($('.box').scrollTop()); }); </script>