date1101吸顶效果

61 阅读1分钟
<!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>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            height: 50000px;
        }

        .header {
            width: 100%;
            height: 150px;
            background-color: red;
            color: white;
            font-size: 40px;
            text-align: center;
            line-height: 150px;
            position: fixed;
            top: -200px;
            transition: top 0.7s;
        }

        .btn {
            width: 100px;
            height: 100px;
            background-color: pink;
            position: fixed;
            right: 50px;
            bottom: 50px;
            display: none;
            border: none;
            font-size: 20px;
            color: orange;
            font-weight: 800;
        }
    </style>
</head>

<body>
    <div class="header">顶部</div>
    <button class="btn">回到顶部</button>

    <script>
        // 获取标签
        let oDiv = document.querySelector('.header');
        console.log(oDiv);
        let oBtn = document.querySelector('.btn');


        // 添加滚动事件  
        // 给顶部标签对象
        window.onscroll = function () {
            if (document.documentElement.scrollTop >= 300) {
                oDiv.style.top = 0;
                oBtn.style.display = 'block';
            } else {
                oDiv.style.top = -200 + 'px';
                oBtn.style.display = 'none';
            }
        }

        // 添加点击事件
        // 给button的页面距离设置为0
        window.onclick = function () {
            document.documentElement.scrollTop = 0;
        }
    </script>
</body>

</html>