«

回到顶部

yang 发布于 阅读:382 JS基础阶段


<!DOCTYPE html>
<html 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>
            .toTop {
                position: fixed;
                right: 20px;
                bottom: 20px;

                width: 40px;
                background: #f00;
                color: #fff;
                text-align: center;
                padding: 10px;
                cursor: pointer;
                display: none;
            }
        </style>
    </head>
    <body>
        <div class="toTop">回到顶部</div>

        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>
        <h1>今天星期二</h1>

        <script>
            //进阶版:回到顶部加上动画效果
            //给按钮绑定点击事件,点击时滚动条滚动到顶部
            let toTop = document.querySelector(".toTop");
            toTop.onclick = function () {
                let y = window.scrollY; //点击时获取到滚动条滚动的高度

                let timer = setInterval(function () {
                    y -= 50;
                    window.scrollTo(0, y);
                    if (y <= 0) {
                        clearInterval(timer); //当滚动条滚动到顶部时,清除定时器,结束动画
                    }
                }, 20);
            };

            // 高级版:刚开始不显示“回到顶部”,滚动条滚动到指定的位置时才显示
            window.onscroll = function () {
                if (window.scrollY >= 300) {
                    toTop.style.display = "block";
                } else {
                    toTop.style.display = "none";
                }
            };
        </script>
    </body>
</html>

回到顶部

版权所有:微4e
文章标题:回到顶部
除非注明,文章均为 微4e 原创,请勿用于任何商业用途,禁止转载

推荐阅读:


扫描二维码,在手机上阅读
请先 登录 再评论