js點擊按鈕滾動到頂部

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>回到頂部scrollTop</title>
    <style type="text/css">
        #button{width: 50px;height: 50px;border-radius: 50%;background: #000;opacity: 0.4;position: fixed;bottom: 30px;right: 30px;display: none;}
        .content{background:-webkit-gradient(linear, 0 0, 0 100%, from(green), to(yellow));height: 2000px;width: 100%;}
    </style>

</head>
<body>
<div id="button"></div>
<div class="content"></div>
<script>
    // 回到頂部scrollTop
    // 總時間(duration):500ms
    //頻率(interval):多長時間走一步 10ms
    //總距離(target):當前的位置(當前的scrollTop值)目標位置0;
    // 步長(step):每一次走的距離  target/duration * interval 每一次走的距離

    var button = document.getElementById("button");
    window.onscroll = computedDisplay;
    function computedDisplay(){
        var curTop = document.documentElement.scrollTop || document.body.scrollTop;
        var curHeight = document.documentElement.clientHeight || document.body.clientHeight;
        button.style.display = curTop>curHeight?"block":"none";
    }
    button.onclick = function(){
        this.style.display = "none";
        window.onscroll = null;
        var duration = 500,interval = 10,target = document.documentElement.scrollTop || document.body.scrollTop;
        var step = (target/duration) * interval;

        var timer = window.setInterval(function(){
            var curTop = document.documentElement.scrollTop || document.body.scrollTop;
            if(curTop ===0){
                window.clearInterval(timer);
                window.onscroll = computedDisplay;//動畫結束后方法重新綁定
                return;
            }
            curTop -=step;
            document.documentElement.scrollTop = curTop;
            document.body.scrollTop = curTop;
        },interval);

    }

</script>
</body>
</html>

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容