案例:判斷與頂部距離,點(diǎn)擊按鈕動(dòng)態(tài)返回頂部

css

<style>
        #top {
            width: 50px;
            height: 30px;
            line-height: 30px;
            border-radius: 5px;
            background: skyblue;
            color: white;
            position: fixed;
            bottom: 100px;
            right: 30px;
            padding: 0 20px;
            cursor: pointer;
            display: none;
        }
    </style>

body

<body>

    1<br>
    1<br>
    <!--  n個(gè) 1<br>  節(jié)約控件 刪除了-->

    <div onclick="topUp()" id="top">
        回頂部
    </div>
    <script>
        (function () {
            var $ = function (id) {
                return document.getElementById(id);
            }
            window.$ = $;
        })()

        var t;
        window.onscroll = function () {

            var topUp = document.body.scrollTop || document.documentElement.scrollTop;

            if (topUp > 200) {
                // document.getElementById("top").style.display = "block";
                $("top").style.display = "block";
            } else {
                $("top").style.display = "none";
            }

        }

        function topUp() {
            t = setInterval(function () {
                var st = document.body.scrollTop || document.documentElement.scrollTop;
                var speed = Math.floor(-st / 5);
                document.body.scrollTop = document.documentElement.scrollTop = st + speed;

                if (st === 0) {
                    clearInterval(t);
                }
            }, 100)


            // document.body.scrollTop = 0;
            // document.documentElement.scrollTop = 0;
        }
    </script>

</body>
image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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