返回顶部实现方式

时间:2021-07-25 13:19:10

通过html的a标签链接到文档顶部

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{margin: 0;padding: 0}
        div{height: 1000px;background: pink}       
     button{height:30px;width:80px;position:fixed;bottom:5px;right:5px}
        a{text-decoration: none}
    </style>
</head>
<body>
<div id="top">
内容区
</div>
<button><a href="#">返回顶部</a></button>   <!--给按钮设置一个链接,href可直接写#表示返回到顶部,也可通过#id连接到指定的id标签,只能连接到id标签-->

 

通过js的scroll函数

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{margin: 0;padding: 0}
        div{height: 1000px;background: pink}
        button{height:30px;width:80px;position:fixed;bottom:5px;right:5px}
        a{text-decoration: none}
    </style>
</head>
<body>
<div id="top">
内容区
</div>
<button><a href="javascript:scroll(0,0)">返回顶部</a></button>
</body>
</html>

 

上述两种方式,返回顶部的按钮会一直显示。

通过window对象的scrollTop()实现,$(window).scrollTop()表示滚动条距离上方的距离,$(window).scrollTop(0)表示设置距离为0即返回顶部

<head>
    <meta charset="UTF-8">
    <title>title</title>
    <script src="https://libs.baidu.com/jquery/2.1.4/jquery.js"></script>
    <style>
        *{margin: 0;padding: 0}
        div {height: 1000px;background: pink}
        button{height:30px;width:80px;position:fixed;bottom:5px;right:5px}
        .hide{display:none}  /*如果class包含hide则不显示*/
    </style>
</head>
<div>
    内容区
</div>
<button class="returnTop hide" onclick="returnTop()">返回顶部</button>
<script>
    window.onscroll=function () {  //滚动条事件,只要滚动条滚动就触发该事件
        if ($(window).scrollTop()>250){
           $('.returnTop').removeClass('hide')  //如果滚动条距离上方超过250px,则删除按钮的hide,即显示“返回顶部”按钮
       } else{
           $('.returnTop').addClass('hide')}   //如果滚动条距离上方不超过250px,则增加按钮的hide,即不显示“返回顶部”按钮
    }

    function returnTop() {
        $(window).scrollTop(0)  //如果点击“返回顶部”按钮,设置滚动条距离上方距离为0,即返回顶部
    }
</script>