HTMLElement.offsetTop 适用于静态父元素

标签 html

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/

相关文章:

html - 如何在 HTML5 中标记复杂的状态指示器?

javascript - 如何更改 jquery easyPiechart 的百分比值

javascript - AngularJS 表单验证 : has-error not showing for ng-required fields

javascript - 从选择值中获取 div id

javascript - 地理定位 watch 不会持续触发

javascript - 如何使用javascript根据背景颜色更改文本颜色?

javascript - wIdth/height 继承 div 的行为

javascript - 如何从 DOM 中删除 div 及其内容

ipad - iPad 离线应用程序上的 HTML5 应用程序缓存 - 如果服务器不可用则无法工作?

HTML 并启用 div 的水平滚动但隐藏水平滚动条