长风破浪会有时
直挂云帆济沧海

js回到顶部代码

var gotop = document.getElementById("gotop");
    var timer = null; 
    var isTop = true; 
    window.onscroll = function(){        
        let osTop = document.documentElement.scrollTop || document.body.scrollTop; 
        let clientHeight = document.documentElement.clientHeight; 
        if(osTop >= 100){  
            gotop.style.display = 'block';
        }else{         //否则隐藏
            gotop.style.display = 'none';
        }
        if(!isTop){
            clearInterval(timer);
        }
        isTop = false;
    }

    gotop.onclick = function(){
        timer = setInterval(function(){
            let osTop = document.documentElement.scrollTop || document.body.scrollTop;
            let speed = Math.floor(-osTop / 6);
            document.documentElement.scrollTop = document.body.scrollTop = osTop + speed;
            isTop = true; 
            if(osTop == 0){
                clearInterval(timer);
            }
        },30);
    }
赞(1)
未经允许不得转载:阿锋哥前端开发经验分享 » js回到顶部代码
分享到: 更多 (0)

几百块就能做营销型企业网站?

查看详情