JavaScript實(shí)現(xiàn)回到頂部

實(shí)現(xiàn)回到頂部,先快后慢,在回到頂部過程中可以滾動滾輪打斷回到頂部過程。
回到頂部按鈕在第二屏才會出現(xiàn),回到第一屏消失。

<!DOCTYPE html>
<!--實(shí)現(xiàn)回到頂部,先快后慢,在回到頂部過程中可以滾動滾輪打斷回到頂部過程。-->
<!--回到頂部按鈕在第二屏才會出現(xiàn),回到第一屏消失。-->
<html>
<head>
    <meta charset="utf-8">
    <title>回到頂部實(shí)例</title>
</head>
<script type="text/javascript">
    window.onload = function(){
        var obtn = document.getElementById('btn');
        var clientHeight = document.documentElement.clientHeight;
        var timer = null;
        var isTop = true;
        //滾動條滾動時觸發(fā)
        window.onscroll=function() {
            var osTop = document.documentElement.scrollTop||document.body.scrollTop;
            if (osTop>clientHeight) {
                obtn.style.display ='block';
            }else{
                obtn.style.display = 'none';
            }
            if (!isTop) {
                clearInterval(timer);
            }
            isTop=false;
        }
        //點(diǎn)擊返回頂部按鈕觸發(fā)
        obtn.onclick = function(){
            clearInterval(timer);
            timer =setInterval(function(){
                var osTop = document.documentElement.scrollTop||document.body.scrollTop;
                var ispeed = Math.floor(-osTop/7);//對浮點(diǎn)數(shù)向下取整,小于或者等于該參數(shù)的最大整數(shù)。
                document.documentElement.scrollTop = document.body.scrollTop = osTop+ispeed;
                isTop=true;
                console.log(osTop);
                if (osTop==0) {
                    clearInterval(timer);
                }
            },30)
        }
    }
</script>
<style>
body
{
    background-color: lightblue;
    height: 7001px;
}
a
{
    position: fixed;
    right: 20px;
    bottom: 20px;
    display: none;
}
</style>
<body>
    <a href="javascript:;" id="btn">回到頂部</a>
</body>
</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容