编程语言
首页 > 编程语言> > javascript – jQuery offset().top返回错误的值 – 带边距的错误

javascript – jQuery offset().top返回错误的值 – 带边距的错误

作者:互联网

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

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

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

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

解决方法:

你的问题:

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

我建议你把.container定位到亲戚:

.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()顶部.:
描述:获取相对于文档的匹配元素集中第一个元素的当前坐标.

.POSITION()顶部.:
来自文档:

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

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

$(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>

标签:html,javascript,jquery,css,jquery-animate
来源: https://codeday.me/bug/20191006/1861545.html