jQuery中的位置操作(offset,position,scroll)
offset()
返回距离父元素的偏移量left和top值,把这两个值封装在一个对象中,若想得到具体的值(使用offset().left,offset().top),父元素必须要有定位,否则返回距离文档的值
<style>
* {
margin: 0;
}
.father {
position: relative;//给父元素设置定位
width: 500px;
height: 500px;
background-color: black;
}
.son {
margin-left: 20px;
width: 200px;
height: 200px;
background-color: pink;
}
</style>
<script src="jQuery.min.js"></script>//引入jQuery文件
<body>
<div class="father">
<div class="son"></div>
</div>
<script>
$(function() {
var width = $('.son').offset();
console.log(width);//{top: 0, left: 20}
var height= $('.son').offset().left;
var height1= $('.son').offset().top;
console.log(height);//20
console.log(height1);//0
})
</script>
</body>