HTMLElement.offsetParent - Web API 接口参考 | MDN
HTMLElement.offsetParent
是一个只读属性,返回一个指向最近的(指包含层级上的最近)包含该元素的定位元素或者最近的 table,
td,
th,
body
元素。当元素的 style.display
设置为 "none" 时,offsetParent
返回 null
。offsetParent
很有用,因为 offsetTop 和 offsetLeft 都是相对于其内边距边界的。
HTMLElement.offsetTop - Web API 接口参考 | MDN
HTMLElement.offsetTop
为只读属性,它返回当前元素相对于其 offsetParent 元素的顶部内边距的距离
HTMLElement.offsetLeft - Web API 接口参考 | MDN
HTMLElement.offsetLeft
是一个只读属性,返回当前元素左上角相对于 HTMLElement.offsetParent 节点的左边界偏移的像素值。 (行内元素特殊,见文档)
<style>
* {
margin: 0
}
/* 有position: relative; 和没有时候的区别,子元素对应的offsetParent不一样了 */
#father {
/* position: relative; */
width: 150px;
height: 150px;
background: red;
}
#son {
margin-top: 10px;
margin-left: 10px;
width: 50px;
height: 50px;
background: blue;
line-height: 50px;
text-align: center;
}
</style>
<body>
<div id="father">
<div id="son">son</div>
</div>
</body>
<script>
var son = document.getElementById("son");
console.log(son.offsetParent)
console.log(son.offsetLeft)
console.log(son.offsetTop)
</script>
垂直方向上的margin相关问题:理解 margin 垂直重叠的原因和解决方案_real_metrix的博客-CSDN博客_垂直margin重叠是为什么