0
点赞
收藏
分享

微信扫一扫

JavaScript练习小案例-----回到顶部

mjjackey 2022-02-06 阅读 86
 <style>
        * {
           margin: 0;
           padding: 0;
        }

        body{
            height: 3000px;
        }

        .header{
            width: 100%;
            height: 40px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 30px;
            color: #fff;
            background-color: skyblue;

            transition: top .5s linear;


            position: fixed;
            top: -80px;
            left: 0;
        }


        .goTop{
            width: 50px;
            height: 50px;
            background-color: pink;
            font-size: 20px;
            text-align: center;
            line-height: 25px;
            color: #fff;


            position: fixed;
            bottom: 10px;
            right: 10px;

            display: none;
        }
    </style>
</head>
<body>
    <div class="header">顶部通栏</div>
    <div class="goTop">回到顶部</div>


    <script>

        // 获取元素
        var header = document.querySelector(".header");
        var goTop = document.querySelector(".goTop");

        // 绑定滚动事件
        window.onscroll = function(){
            // 获取浏览器卷去的高度
            var height = document.documentElement.scrollTop || document.body.scrollTop;

            // 判断卷去的高度
            if (height >= 300) {
                // 显示
                header.style.top = "0px";
                goTop.style.display = "block";

            }else{
                // 隐藏
                header.style.top = "-80px";
                goTop.style.display = "none";
            }

            // 绑定点击事件
            goTop.onclick = function(){
                // 让页面滚动回顶部
                window.scrollTo({
                    top: 0,
                    behavior: "smooth"
                })
            }

        }

    </script>
</body>
举报

相关推荐

0 条评论