1.元素偏移量offset系列
offset系列相关属性可以动态得到该元素的位置(偏移),大小等
(1)获得的元素距离带有定位的父元素的位置
(2)获得的元素自身的大小(宽度高度)
注意,返回的数值不带单位
2.offset系列常用属性
| offset系列属性 | 作用 |
| element.offsetParent | 返回作为该元素带有定位的父级元素,如父级元素都没有定位则返回body |
| element.offsetTop | 返回元素带有相对定位的父元素上方的偏移 |
| element.offsetLeft | 返回元素带有相对定位的父元素左边框的偏移 |
| element.offsetWidth | 返回自身包括padding,边框,内容去的宽度,返回值不带单位 |
| element.offsetHeight | 返回自身包括padding,边框,内容区的高度,返回数值不带单位 |
<style>
* {
margin: 0;
padding: 0;
}
.father {
position: relative;
width: 200px;
height: 200px;
background-color: pink;
margin: 150px;
}
.son {
width: 150px;
height: 150px;
background-color: grey;
margin-left: 20px;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
<script>
var father = document.querySelector('.father');
var son = document.querySelector('.son');
console.log(father.offsetTop);//150
console.log(father.offsetLeft);//150
//father没有定位时或无father,offsetLeft按照body进行计算,得到结果170
//father有相对定位时,offsetLeft按照father计算,得到结果20
console.log(son.offsetLeft);
console.log(father.offsetWidth);//200
console.log(father.offsetHeight);//200
console.log(son.offsetWidth);//150
console.log(son.offsetHeight);//150
//返回带有定位的父元素
console.log(son.offsetParent);//<div></div>
console.log(father.offsetParent);//<body></body>
</script>
</body>
offset与style的区别
| offset | style |
| offset可以获得任意样式表中的样式值 | style只能得到行内样式表中的样式值 |
| o |

最低0.47元/天 解锁文章
434

被折叠的 条评论
为什么被折叠?



