回到顶部案例

149 阅读1分钟

image.png

HTML部分

<body>
    <button id="btn">回到顶部
    </button>
</body>

设置按钮

css部分

 button{
        position: fixed;
        bottom: 30px;
        right: 30px;
        display: none;
       
       }
       body{
        height: 4000px;
        }
        .active{
            display: block;
        }

设置盒子,盒子的高度要超过页面的高度

按钮要在下拉一定距离时按钮才出现

js部分

属性

scrollTop 读或写当前元素的滚动条垂直位置

onscroll 当元素被滚动时,相应的事件处理程序将会被调用

 window.onscroll=function(){
 //如果到顶部的距离大于窗口的高度就显现(与css联动)
     if(document.documentElement.scrollTop>window.innerHeight){
            
        btn.classList.add("active")
         }else{
          
        btn.classList.remove("active")
    }
    }
   
    btn.addEventListener("click", clickHandler);
//点击,
    function clickHandler() {
        let backtime = setInterval(function () {
            var distY = document.documentElement.scrollTop
          
            if (distY == 0){
                clearInterval();
                return;
              
            } 
            var speed = Math.ceil(distY/50);
 //设置速度,速度是距离高度的一半。
//高度为高度减时间
            document.documentElement.scrollTop=distY-speed;
          
        }, 1);
        
    }  

完整代码

<!DOCTYPE html>
<body lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
      button{
        position: fixed;
        bottom: 30px;
        right: 30px;
        display: none;
       
       }
       body{
        height: 4000px;
        }
        .active{
            display: block;
        }
      
    </style>
    
</head>
<body>
    <button id="btn">回到顶部
    </button>
</body>
<script>
    window.onscroll=function(){
        if(document.documentElement.scrollTop>window.innerHeight){
            
        btn.classList.add("active")
         }else{
          
        btn.classList.remove("active")
    }
    }
   
    btn.addEventListener("click", clickHandler);
    function clickHandler() {
        let backtime = setInterval(function () {
            var distY = document.documentElement.scrollTop
          
            if (distY == 0){
                clearInterval();
                return;
              
            } 
            var speed = Math.ceil(distY/50);
       
            document.documentElement.scrollTop=distY-speed;
          
        }, 1);
        
    }  
</script></html>