gpt4 book ai didi

javascript - 在可滚动的 div 中滚动到顶部

转载 作者:可可西里 更新时间:2023-11-01 13:26:18 24 4
gpt4 key购买 nike

我在一个可滚动的 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>

最佳答案

您需要将 .test 的当前 scrollTop() 位置添加到您的数学中

$(".test").on("click", "p", function(evt) {

var $test = $(evt.delegateTarget), // The ".test" parent element
$p = $(this); // The clicked "p" element

$test.stop().animate({
scrollTop: $p.offset().top + $test.scrollTop()
}, 800);

});
body{margin:0;}
.test{overflow:auto; height:200px; width:300px;}
<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>

关于javascript - 在可滚动的 div 中滚动到顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37665515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com