jquery - 为什么position().top在没有任何边距或填充的元素上显示8?

标签 jquery

为什么这段代码的控制台结果是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/

相关文章:

javascript - 如何从jquery中的对象中删除值

javascript - 输入框不让我输入

javascript - 如何在C#中使用toaster显示ajax返回的消息?

jquery - Chrome 扩展开发 : Modifying the DOM using jQuery

javascript - Jquery 在悬停时更改图像并在鼠标悬停时设置默认图像

jquery - 显示在缩略图上单击的覆盖图和相关图像

javascript - 函数说它是 "not defined"

javascript - 从选定的下拉列表中将值附加到文本区域而不删除以前的值

javascript - 如何用css展开一个div

javascript - 更改标签值时出错