jQuery offset().top返回错误的值 - 带有margin的错误

use*_*654 12 html javascript css jquery jquery-animate

如果您尝试从父级中的列表元素获取顶部偏移量,并且该父级位于顶部,则会得到错误的值.

http://jsbin.com/yuxacuduna/1/edit?html,css,js,console,output

尝试删除margin-top的上.container元素,你会看到它的工作.

这个问题的解决方案是什么?

Jai*_*Jai 25

你的问题:

这个问题的解决方案是什么?

我建议你定位.containerrelative:

.container{
  margin-top:100px;
  background:yellow;
  height:600px;
  width:300px;
  overflow-y:auto;
  overflow-x:hidden;
  position:relative; /*<---add this*/
}
Run Code Online (Sandbox Code Playgroud)

在您的脚本使用中.position().top,它将使您的生活更轻松:

$('.container li:nth-child(7)').css("background", "red");
$('.container').animate({
    scrollTop: $('.container li:nth-child(7)').position().top
});
Run Code Online (Sandbox Code Playgroud)

.offset().top:
说明:获取相对于文档的匹配元素集中第一个元素的当前坐标.

.position().top:
来自文档:

描述:获取相对于偏移父元素的匹配元素集中第一个元素的当前坐标.

.position().top 如果父级相对定位,则从顶部到父级计算.

$(function() {
  $('.container li:nth-child(7)').css("background", "red");
  $('.container').animate({
    scrollTop: $('.container li:nth-child(7)').position().top
  });
});
Run Code Online (Sandbox Code Playgroud)
html,
body {
  margin: 0;
  padding: 0;
}
.container {
  margin-top: 100px;
  background: yellow;
  height: 600px;
  width: 300px;
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;
}
.container ul {
  margin: 0;
  padding: 0;
  list-style: none outside none;
}
.container li {
  background: blue;
  display: block;
  height: 150px;
  width: 100%;
  padding: 10px;
  margin-bottom: 5px;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <ul>
    <li>asdasd</li>
    <li>asdasd</li>
    <li>asdasd</li>
    <li>asdasd</li>
    <li>asdasd</li>
    <li>asdasd</li>
    <li>asdasd77</li>
    <li>asdasd</li>
    <li>asdasd</li>
    <li>asdasd</li>
    <li>asdasd</li>
  </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 相对定位ftw! (2认同)
  • 四年的答案今天仍然有效,你救了我的命 (2认同)

Nat*_*ate 7

如果您的某些内容是图像,您也可能会遇到此问题。如果您在 document.ready() 中调用 .offset(),则图像可能尚未加载。尝试将您的 .offset() 调用移动到 window.load()。

  • 这应该是正确的答案。在 document.ready() 中使用 offset.top 会返回奇怪的结果。我得到的数字大于我的视口,但使用 window.load() 有效! (2认同)