javascript - jQuery offset().top 返回错误值 - 边距错误

标签 javascript jquery html css jquery-animate

如果您尝试从父级中的列表元素获取顶部偏移量,而该父级不位于顶部,您将得到错误的值。

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

尝试删除 .container 元素上的 margin-top,您会发现它会起作用。

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

最佳答案

您的问题:

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

我建议你将 .container 定位到 relative:

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

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

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

.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
  });
});
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;
}
<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>

关于javascript - jQuery offset().top 返回错误值 - 边距错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29277608/

相关文章:

JavaScript 字符串 : get content of two standing next to each other pieces of content and wrap them together

javascript - 通过javascript、ajax发送到服务器的base64代码

javascript - 下拉语义-UI : Keep the button value by change event

html - 设计 reddit 小部件的样式

javascript - 悬停/鼠标悬停时音频播放,可以在没有 jQuery 的情况下吗?

javascript - 在另一张图片上显示超棒的字体图标

javascript - 使用下一个和上一个按钮在 div 之间滑动

javascript - 根据特定属性的值获取元素的类或 ID 名称

javascript - 条件形式取决于选择列表中的答案不起作用

php - 如何从 html 调用 Php 函数