滚动条

72 阅读1分钟
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .but {
            position: fixed;
            bottom: 0px;
            right: 0px;
        }
    </style>
    <style>
        body {
            height: 30000px;
        }
    </style>
</head>

<body>



    <button class="but" id="btn">回到顶部</button>
    <script>
        window.onscroll = function () {
            console.log(document.documentElement.scrollTop || document.body.scrollTop)

            if ((document.documentElement.scrollTop || document.body.scrollTop) > 0) {
                document.getElementById("btn").style.display = "block";            
            } else {
                document.getElementById("btn").style.display = "none";
            }
        }



        btn.onclick = function () {
            window.scrollTo({
                left: 0,
                top: 0
            })
        }
    </script>
</body>

</html>