jQuery回到顶部

回到顶部

如果是一瞬间回到顶部,那很简单,但是如果想要平滑的回到顶部,那我们可以先计算出当前滚动条和顶部的位置,然后设置一个时间,表示在这个时间点到达顶部,并且是分多次的,每次设置一定的时间,计算出每次距离之后定时往顶部拉进距离。

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>03_回到顶部</title>
  <style>
    #to_top {
      width: 30px;
      height: 40px;
      font: 14px/20px arial;
      text-align: center;
      background: #06c;
      position: fixed;
      cursor: pointer;
      color: #fff;
      left: 1050px;
      top: 500px;
    }
  </style>
</head>
<body style="height: 2000px;">
  <div style="border:1px solid black;width:100px;height:150px;overflow:auto">
    This is some text. This is some text. This is some text. This is some text.
    This is some text. This is some text. This is some text. This is some text.
    This is some text. This is some text. This is some text. This is some text.
    This is some text. This is some text. This is some text. This is some text.
    This is some text. This is some text. This is some text. This is some text.
    This is some text. This is some text. This is some text. This is some text.
    his is some text.
  </div>
  <br>
  <br>
  <br>
  <button id="btn1">得到scrollTop</button>
  <button id="btn2">设置scrollTop</button>
  
<div id="to_top">返回顶部</div>

<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript">
  $('#to_top').click(function () {
    // 瞬间滚到顶部,直接定义距离为0,没什么特效
    //$('html,body').scrollTop(0)

    // 平滑滚到顶部
      // 总距离
    var $page = $('html,body')
    //兼容chrome和ie,获取滚动条当前距离顶部的距离
    var distance = $('html').scrollTop() + $('body').scrollTop()
      // 总时间
    var time = 500
      // 间隔时间
    var intervalTime = 50
    //单元移动的距离,每一次移动的距离
    //一共需要移动的次数=(time/intervalTime)
    //每次需要移动的距离=distance/(time/intervalTime)
    var itemDistance = distance/(time/intervalTime)
      // 使用循环定时器不断滚动
    var intervalId = setInterval(function () {
      distance -= itemDistance
      // 到达顶部, 停止定时器
      if(distance<=0) {
        distance = 0 //修正
        clearInterval(intervalId)
      }
      $page.scrollTop(distance)
    }, intervalTime)

  })
</script>
</body>

</html>

 

界面:

jQuery回到顶部

 

上一篇:UVA10803 Thunder Mountain【Floyd算法】


下一篇:ANY,SOME,ALL 在SQL语句中的区别?