返回顶部

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>返回顶部</title>
    <style>
        body{
            height: 3000px;
        }
        #box{
            height: 80px;
            width: 30px;
            background: orange;
            border:1px red solid;
            cursor: pointer;
            position:fixed;
            bottom: 50px;
            right: 50px;
            display: none;
        }
    </style>
</head>
<body>
    <div id="box">返回顶部</div>
</body>
<script>
    var oBox = document.getElementById("box");
    var speed = 10;
    var time = null;
    window.onscroll = function(){

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

        if (Top<=0) {
            clearInterval(time);
        };

        if (Top>300) {
            oBox.style.display = "block";
        }else{
            oBox.style.display = "none";
        };
    }
    oBox.onclick=function(){
        time = setInterval(move,1)
        function move(){
            document.body.scrollTop -= speed;
            document.documentElement.scrollTop-= speed;
            //console.log(document.body.scrollTop)
        }
    }
</script>
</html>
原文地址:https://www.cnblogs.com/jakning/p/4241854.html