首页 > 解决方案 > 重复单击时单击事件中的jQuery scrollTop无法正常工作

问题描述

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

这是代码:

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

标签: javascriptjqueryhtmlcss

解决方案


你可以做的是使用这样的函数scrollTop: $('WhereYouWantToScroll').offset().top 所以你的例子可以很容易地通过在 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>


推荐阅读