返回
BOM之元素三大系列之偏移量 offset 系列
前端
2023-10-13 01:38:14
offset 概述
offset 翻译过来就是偏移量,我们使用 offset 系列相关属性可以动态得到该元素的位置(偏移)、大小等。
获得元素距离带有定位父元素的偏移量
offset()
console.log(ele.offsetParent.offsetLeft) // 距离父元素的左边距离
console.log(ele.offsetParent.offsetTop) // 距离父元素的上边距离
获得元素在页面中的位置(相对于根元素)
offset()
console.log(ele.offsetLeft) // 距离文档左边距离
console.log(ele.offsetTop) // 距离文档上边距离
offsetParent
offsetParent
元素的定位父元素,如果没有,则返回null
console.log(ele.offsetParent) // ele 的定位父元素
offsetWidth
offsetWidth
元素的宽度,包括 padding,不包括 border 和 margin
console.log(ele.offsetWidth) // ele 的宽度
offsetHeight
offsetHeight
元素的高度,包括 padding,不包括 border 和 margin
console.log(ele.offsetHeight) // ele 的高度
offsetTop
offsetTop
元素的顶端距离其定位父元素顶端的距离,如果没有定位父元素,则返回元素距离文档顶端的距离
console.log(ele.offsetTop) // ele 距离其定位父元素顶端的距离
offsetLeft
offsetLeft
元素的左端距离其定位父元素左端的距离,如果没有定位父元素,则返回元素距离文档左端的距离
console.log(ele.offsetLeft) // ele 距离其定位父元素左端的距离
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="parent">
<div id="child">
<p>Hello World</p>
</div>
</div>
<script>
const parent = document.getElementById('parent')
const child = document.getElementById('child')
console.log(child.offsetParent) // parent
console.log(child.offsetLeft) // child 距离其定位父元素左端的距离
console.log(child.offsetTop) // child 距离其定位父元素顶端的距离
console.log(child.offsetWidth) // child 的宽度
console.log(child.offsetHeight) // child 的高度
</script>
</body>
</html>
总结
offset 系列相关属性可以动态得到该元素的位置(偏移)、大小等。
在实际开发中,我们经常会使用 offset 系列相关属性来动态获取元素的位置和大小。