回到顶部

效果

回到顶部一般的网站都有,具体效果如下:

当滑动到一定距离(通常是一屏)后,某个地方会出现“返回顶部”按钮(通常是右下角),点击按钮可以回到顶部,然后按钮隐藏(或其他效果,比如变得透明)。

代码

  • html
1
2
3
4
5
6
<main>
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
</main>
<a href="javascript:void(0);" id="btn" title="回到顶部"></a>
  • css
    说实话,css部分没什么需要特别注意的地方。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    *{
    margin: 0;
    padding: 0;
    }
    main{
    width:1000px;
    margin: 0 auto;
    }
    #box1{
    height: 890px;
    background-color: #eee;
    margin-bottom: 10px;
    }
    #box2{
    height: 590px;
    background-color: orange;
    margin-bottom: 10px;
    }
    #box3{
    height: 400px;
    background-color: pink;
    }
    #btn{
    position: fixed;
    display: none;
    width: 40px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    bottom: 20px;
    right: 5%;
    background-color: #ddd;
    text-decoration: none;
    }
  • javascript
    重头戏

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    window.onload = function () {
    var btn = document.getElementById('btn');
    var clientHeight = document.documentElement.clientHeight;
    var timer = null;
    var isTop = true;

    window.onscroll = function () {
    var myTop = document.documentElement.scrollTop || document.body.scrollTop;
    if(myTop >= clientHeight){
    btn.style.display = 'block';
    }else{
    btn.style.display = 'none';
    }

    //滑动过程中滑动滚动条的话也结束定时器
    if(!isTop){
    clearInterval(timer);
    }
    isTop = false;
    }
    btn.onclick = function () {
    timer = setInterval(function () {
    var myTop = document.documentElement.scrollTop || document.body.scrollTop;
    var speed = Math.ceil(myTop / 6);
    document.documentElement.scrollTop = document.body.scrollTop = myTop - speed;

    isTop = true;
    if(myTop == 0){
    clearInterval(timer);
    }
    }, 30);
    }
    }

原理

本次通过使用js来实现回到顶部效果,而不是用html的锚点,达到平滑的滚动效果。关键点:scrollTop,clientHeight,setInterval()。

按钮的隐藏与消失

首先是获取屏幕的高度clientHeight,然后通过判断滑动的距离scrollTop与高度的大小来实现效果。滑动大于一屏高度时将按钮显示,其他隐藏。

滑到顶部

通过使用定时器setInterval来实现,当回到顶部时,取消定时器。