为什么这段代码的控制台结果是8
?我期待 0
,因为 .title
和 .parent
之间没有任何边距、填充等。
console.log($('#title').position().top);
.parent {
background: lightgreen;
height: 79px;
}
.title {
background: gold;
line-height: 54px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
<div class='title' id='title'>lorem ipsum</div>
</div>
最佳答案
这是因为大多数浏览器默认在 body
中添加了 margin
。您需要删除它:
console.log($('#title').position().top);
body {
margin: 0;
}
.parent {
background: lightgreen;
height: 79px;
}
.title {
background: gold;
line-height: 54px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
<div class='title' id='title'>lorem ipsum</div>
</div>
我建议您使用重置样式表来标准化每个浏览器中所有 CSS 的起点。
But position is relative to parent, not to body!
几乎 - 它与偏移父级有关(请参阅 jQuery docs )。一个微小但至关重要的区别。这意味着最接近的父元素不是 position: static
,因为它们默认都是这样。由于您没有这些内容,因此它会上升到body
。要解决此问题,请在 .parent
上设置 position:relative
:
console.log($('#title').position().top);
.parent {
position: relative;
background: lightgreen;
height: 79px;
}
.title {
background: gold;
line-height: 54px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
<div class='title' id='title'>lorem ipsum</div>
</div>
关于jquery - 为什么position().top在没有任何边距或填充的元素上显示8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53228982/