https://jsfiddle.net/6vqbLm5c/29/
HTML:
<div>
<p id="par">paragraph</p>
</div>
CSS:
p {
margin:0;
}
div {
padding: 10px;
}
body {
margin:0;
}
p.offsetTop 返回 10px。我的理解是父元素 div 默认设置了静态位置,并根据 offsetTop documentation offsetTop 是距离最近的相对定位父元素顶部的像素数。那么,为什么即使 p 没有相对定位的父元素,它仍然返回 10px?
最佳答案
区别似乎在于 the description for position: relative
:
The element is positioned according to the normal flow of the document, and then offset relative to itself based on the values of
top
,right
,bottom
, andleft
. The offset does not affect the position of any other elements; thus, the space given for the element in the page layout is the same as if position werestatic
.
和 the documentation for the visual formatting model :
The normal flow is triggered when the CSS position is set to the value
static
orrelative
, and if the CSSfloat
is set to the valuenone
.
...
Instatic
positioning, triggered by the valuestatic
of theposition
property, the boxes are drawn at the exact position defined by the normal flow layout.
也就是说,当页面上不存在没有定位的元素时,所有元素都属于“正常流”,每个元素的定位由其每个祖先确定。
这在您申请 margin
时变得很明显至 <body>
; offsetTop
增加以适应边距:
var p = document.getElementById('par');
console.log(p.offsetTop)
p {
margin: 0;
}
.container {
padding: 20px;
}
body {
margin: 10px;
}
<div class="container">
<p id="par">paragraph</p>
</div>
并且可以在修改<html>
时进一步增强本身:
var p = document.getElementById('par');
console.log(p.offsetTop)
p {
margin: 0;
}
.container {
padding: 20px;
}
body {
margin: 10px;
}
html {
padding: 5px;
}
<div class="container">
<p id="par">paragraph</p>
</div>
因此,offsetTop
增加以容纳祖先,不管没有定位的祖先。
关于HTMLElement.offsetTop 适用于静态父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51508872/