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

时间:2018-12-05 11:11:58

标签: javascript jquery html css

在我的HTML中,另一个<div>的底部有一个名为lastText的{​​{1}}。我需要单击一个按钮并滚动到<div>。当我单击按钮时,它滚动到lastText,但是当我再次单击它时,它滚动到顶部和底部之间的某个位置。当我滚动到中间的某个位置并单击按钮时,它不会滚动到<div>。因此,基本上,只有当我从最上方开始滚动时,滚动才能正常工作。在lastText中任何位置单击按钮时,我需要滚动到lastText。我该怎么解决?

代码如下:

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

2 个答案:

答案 0 :(得分:1)

您可以做的是使用类似scrollTop: $('WhereYouWantToScroll').offset().top的函数 因此,您可以轻松地通过div顶部和底部之间的if切换来完成示例

    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>

答案 1 :(得分:1)

纯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>