关于javascript:JavaScript点击回到顶部

7次阅读

共计 617 个字符,预计需要花费 2 分钟才能阅读完成。

次要依靠于滚轮监听实现。scroll 值须要正确的了解

代码实现如下:

<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <title> 回到顶部 </title>
    <style>
        *{
            margin:0;
            padding:0;
        }
        body{height:3000px;}
        #box{
            position:fixed;
            top:0;
            display:none;
            width:100%;
            background-color:black;
            height:60px;
        }
        #top{
            position:fixed;
            right:30px;
            bottom:30px;
            baclground-color:blue;
            width:30px;
            height:30px;
        }
    </style>
</head>
<body>
    <div id='box'></div>
    <div id='top'></div>
    <script>
        window.onscroll = function(){if(window.scrollY >= 300){box.style.display = 'block';}else{box.style.display = 'none';}
        }
        
        var top = document.getElementById('top');
        top.onclick = function(){window.scrollTo(0,200);
        }
    </script>
</body>
</html>
正文完
 0