gpt4 book ai didi

HTMLElement.offsetTop 适用于静态父元素

转载 作者:行者123 更新时间:2023-11-28 02:29:52 46 4
gpt4 key购买 nike

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, and left. 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 were static.

the documentation for the visual formatting model :

The normal flow is triggered when the CSS position is set to the value static or relative, and if the CSS float is set to the value none.

...

In static positioning, triggered by the value static of the position 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/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com