重复单击时,单击事件中的jQuery scrollTop无法正常工作



在我的HTML中,在另一个<div>的底部有一个名为lastText<div>。我需要单击一个按钮并滚动到lastText。当我点击按钮时,它会滚动到<div>,但当我再次点击时,它在顶部和底部之间滚动。当我滚动到中间的某个位置,点击按钮时,它不会滚动到lastText。所以基本上只有当我从最上面开始滚动时,滚动才能正常工作。当从<div>中的任何位置单击按钮时,我需要滚动到lastText。我该如何解决这个问题?

这是代码:

http://jsfiddle.net/aQpPc/202/

纯Javascript解决方案:

function test() {
let el = document.getElementById("lastText");
el.scrollIntoView({behavior: "smooth"});
}
<div id="scrollTest" style="height : 100px; overflow : auto;">
1 - Long Div Scrolling text <br/>
2 - Long Div Scrolling text <br/>
3 - Long Div Scrolling text <br/>
4 - Long Div Scrolling text <br/>
5 - Long Div Scrolling text <br/>
6 - Long Div Scrolling text <br/>
7 - Long Div Scrolling text <br/>
8 - Long Div Scrolling text <br/>
9 - Long Div Scrolling text <br/>
10 - Long Div Scrolling text <br/>
11 - Long Div Scrolling text <br/>
12 - Long Div Scrolling text <br/>
13 - Long Div Scrolling text <br/>
14 - Long Div Scrolling text <br/>
15 - Long Div Scrolling text <br/>
16 - Long Div Scrolling text <br/>
17 - Long Div Scrolling text <br/>
<div id="lastText">last</div>
</div>
<button type="button" onclick="test()">scroll down</button>

您可以使用类似scrollTop: $('WhereYouWantToScroll').offset().top的函数因此,您的示例可以很容易地使用if在div 的顶部和底部之间切换

var isTop = true;
function test() {
if(isTop){
$('#scrollTest').animate({
scrollTop: $('#lastText').offset().top
}, 1000);
}
else{
$('#scrollTest').animate({
scrollTop: $('#scrollTest').offset().top + -10
}, 1000);
}
isTop = !isTop;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="scrollTest" style="height : 100px; overflow : auto;">
1 - Long Div Scrolling text <br/>
2 - Long Div Scrolling text <br/>
3 - Long Div Scrolling text <br/>
4 - Long Div Scrolling text <br/>
5 - Long Div Scrolling text <br/>
6 - Long Div Scrolling text <br/>
7 - Long Div Scrolling text <br/>
8 - Long Div Scrolling text <br/>
9 - Long Div Scrolling text <br/>
10 - Long Div Scrolling text <br/>
11 - Long Div Scrolling text <br/>
12 - Long Div Scrolling text <br/>
13 - Long Div Scrolling text <br/>
14 - Long Div Scrolling text <br/>
15 - Long Div Scrolling text <br/>
16 - Long Div Scrolling text <br/>
17 - Long Div Scrolling text <br/>
<div id="lastText">last</div>
</div>
<button type="button" onclick="test()">scroll down</button>

最新更新