jQuery通过滚动事件实现回顶部效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style type="text/css">
    body{height:1800px;}
    #btn
    {
        position:fixed;
        right:50px;
        bottom:50px;
        width:70px;
        height:20px;
        background-color: aquamarine;
        color:white;
        font-family: "宋体";
        text-align:center;
        font-weight:bold;
        display:none;
        cursor: pointer;
    }
    </style>
    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(function(){
        $(window).scroll(function(){
            if($(this).scrollTop()>300){
                $("#btn").css({"display":"inline-block"});
            }else{
                $("#btn").css({"display":"none"});
            }
        })
        $("#btn").click(function(){
            $("html,body").scrollTop(0);
        })
    })
    </script>
</head>
<body>
    <div id="btn">回到顶部</div>
</body>
</html>

注:按钮效果是通过div效果来实现的,在点击之后,响应点击事件回到顶部,即将scrollTop的值设置为0。

猜你喜欢

转载自blog.csdn.net/gfjserhukher/article/details/84919140