我在可滚动的div中有很多部分,如果点击它,我试图将该部分设置为顶部,它在第一次运行良好但在此之后没有。这是我的尝试
$('p').click (function(){
$('.test').animate({scrollTop: $(this).offset().top}, 800);
});

.test{
overflow:auto;
max-height:300px;
width:300px;
padding-bottom:400px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<p>Section 1</p>
<p>Section 2</p>
<p>Section 3</p>
<p>Section 4</p>
<p>Section 5</p>
<p>Section 6</p>
<p>Section 7</p>
<p>Section 8</p>
<p>Section 9</p>
<p>Section 10</p>
<p>Section 11</p>
<p>Section 12</p>
<p>Section 13</p>
<p>Section 14</p>
<p>Section 15</p>
</div>
&#13;
答案 0 :(得分:2)
您需要将.test
当前scrollTop()
位置添加到数学中
$(".test").on("click", "p", function(evt) {
var $test = $(evt.delegateTarget), // The ".test" parent element
$p = $(this); // The clicked "p" element
$test.animate({
scrollTop: $p.offset().top + $test.scrollTop()
}, 800);
});
&#13;
body{margin:0;}
.test{overflow:auto; height:200px; width:300px;}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<p>Section 1</p>
<p>Section 2</p>
<p>Section 3</p>
<p>Section 4</p>
<p>Section 5</p>
<p>Section 6</p>
<p>Section 7</p>
<p>Section 8</p>
<p>Section 9</p>
<p>Section 10</p>
<p>Section 11</p>
<p>Section 12</p>
<p>Section 13</p>
<p>Section 14</p>
<p>Section 15</p>
</div>
&#13;