一、定义
offsetTop 为只读属性,它返回当前元素相对于其 offsetParent 元素的顶部内边距的距离。
上面提到的内边距,即不包括offsetParent元素边框的长度。
我们再来看下offsetParent是什么:
offsetParent 是一个只读属性,返回一个指向最近的(指包含层级上的最近)包含该元素的定位元素或者最近的 table, td, th, body 元素。
当元素的 style.display 设置为 “none” 时,offsetParent 返回 null。
offsetParent 很有用,因为 offsetTop 和 offsetLeft 都是相对于其内边距边界的。
概念不好理解,绘制成图片如下:
通过上图可知:
offset 表示元素的上外边框到offsetParent元素的内边框的距离。
offsetHeight 表示元素的垂直方向的高度,等于边框+内边距+内容的高度之和。
二、代码实现
<div class="box">
<div class="container">
<div class="content">
content
</div>
</div>
<div class="btn">btn</div>
</div>
const container = document.querySelector('.container')
const content = document.querySelector('.content')
const btn = document.querySelector('.btn')
btn.addEventListener('click', () => {
console.log('content', content.offsetHeight)
console.log('content', content.offsetTop)
console.log('offsetParent', content.offsetParent)
})
<style>
.container {
width: 200px;
height: 200px;
display: flex;
align-items: center;
justify-content: center;
background: gray;
}
.content {
width: 100px;
height: 100px;
background: #fff;
}
</style>
点击打印结果,得到值如下:
根据以上代码,content元素的上外边框到container元素的内边框的距离应该是50,但是得到的结果却是70。content元素的offsetParent为什么是body?
仔细查看定义可知,offsetParent返回一个指向最近的(指包含层级上的最近)包含该元素的定位元素或者最近的 table, td, th, body 元素。因此给元素加上定位属性,position: relative; 再次打印,得到值如下:
.container {
position: relative;
}
三、总结
offsetTop属性表示元素顶部到其offsetParent元素内边框的距离,而offsetParent是最近的定位父元素或最近的table、td、th、body元素。当元素没有定位父元素时,offsetParent默认为body。
以上就是有关offsetTop,offsetHeight 的内容,你理解了吗?