zoukankan      html  css  js  c++  java
  • 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;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>

    界面:

  • 相关阅读:
    若干代码坏味及解法
    编程漫谈(十八):编程三境界
    如何不虚度光阴
    打印预览内嵌浏览器的两种方法
    LODOP多个表格带表格页脚关联
    Akka学习笔记
    Spring和Springboot相关知识点整理
    python接口测试:在一个用例文件中调用另一个用例文件中定义的方法
    使用jmeter对字符串进行加密
    (八十九)c#Winform自定义控件-自定义滚动条(treeview、panel、datagridview、listbox、listview、textbox)
  • 原文地址:https://www.cnblogs.com/anjingdian/p/15564444.html
Copyright © 2011-2022 走看看