关于javascript:JavaScript点击回到顶部

次要依靠于滚轮监听实现。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>

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理