回到顶部的几种方案(js)


注意: 最外层父级不可以设置overflow:scroll;否则失效.解决方法:是在外面在加一层div.
1.锚点

<body style="height:2000px;">
    <div id="topAnchor"></div>
    <a href="#topAnchor" style="position:fixed;right:0;bottom:0">回到顶部</a>
</body>


2.scrollTop

<body style="height:2000px;">
    <button id="test" style="position:fixed;right:0;bottom:0">回到顶部</button>
    <script>
    test.onclick = function(){
        document.body.scrollTop = document.documentElement.scrollTop = 0;
    }
    </script>
</body>

3.scrollTo():scrollTo(x,y)方法滚动当前window中显示的文档,让文档中由坐标x和y指定的
点位于显示区域的左上角,设置scrollTo(0,0)可以实现回到顶部的效果.

<body style="height:2000px;">
    <button id="test" style="position:fixed;right:0;bottom:0">回到顶部</button>
<script>
test.onclick = function(){
    scrollTo(0,0);
}
</script>
</body>

4.scrollBy():scrollBy(x,y)方法滚动当前window中显示的文档,x和y指定滚动的相对量

只要把当前页面的滚动长度作为参数,逆向滚动,则可以实现回到顶部的效果

<body style="height:2000px;">
<button id="test" style="position:fixed;right:0;bottom:0">回到顶部</button>
<script>
test.onclick = function(){
var top = document.body.scrollTop || document.documentElement.scrollTop
scrollBy(0,-top);
}
</script>
</body>

5.scrollIntoView():Element.scrollIntoView方法滚动当前元素,进入浏览器的可见区域.
该方法可以接受一个布尔值作为参数。如果为true,表示元素的顶部与当前区域的可见部分的
顶部对齐(前提是当前区域可滚动);如果为false,表示元素的底部与当前区域的可见部分
的尾部对齐(前提是当前区域可滚动)。如果没有提供该参数,默认为true.

<body style="height:2000px;">
<div id="target"></div>
<button id="test" style="position:fixed;right:0;bottom:0">回到顶部</button>
<script>
test.onclick = function(){
target.scrollIntoView();
}
</script>
</body>

========================================
增加scrollTop的动画效果:

returnTop(){
      let that = this;
      cancelAnimationFrame(this.timer);
      this.timer = requestAnimationFrame(function fn(){
        let oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if(oTop > 0){
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          that.timer = requestAnimationFrame(fn);
        }else{
          cancelAnimationFrame(that.timer);
        } 
      });
}


增加scrollTo()动画效果:

var timer = null;
box.onclick = function(){
cancelAnimationFrame(timer);
    timer = requestAnimationFrame(function fn(){
    var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if(oTop > 0){
            scrollTo(0,oTop-50);
            timer = requestAnimationFrame(fn);
        }else{
            cancelAnimationFrame(timer);
        } 
    });
}

增加scrollBy()动画效果:
var timer = null;
box.onclick = function(){
    cancelAnimationFrame(timer);
    timer = requestAnimationFrame(function fn(){
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if(oTop > 0){
            scrollBy(0,-50);
            timer = requestAnimationFrame(fn);
        }else{
            cancelAnimationFrame(timer);
        } 
    });
}

猜你喜欢

转载自blog.csdn.net/szjSmiling/article/details/81512813