jQuery实现简单的回到顶部totop功能示例

本文实例讲述了jQuery实现简单的回到顶部totop功能。分享给大家供大家参考,具体如下:

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>回到顶部</title>
  <style type="text/css">
   body{
    width: 100%;
    height: 10000px;
   }
   #totop{
    width: 50px;
    height: 50px;
    line-height: 50px;
    background: magenta;
    font-size: 20px;
    position: fixed;
    right: 50px;
    bottom: 50px;
   }
  </style>
 </head>
 <body>
 </body>
 <script src="js/jquery-1.8.3.min.js" ></script>
 <script>
  //写在common.js文件中用来调用即可
  //1获取滚动条当前的位置
  function getScrollTop() {
   var scrollTop = 0;
   if (document.documentElement && document.documentElement.scrollTop) {
    scrollTop = document.documentElement.scrollTop;
   } else if (document.body) {
    scrollTop = document.body.scrollTop;
   }
   return scrollTop;
  };
  //2获取文档完整的高度
  function getScrollHeight() {
   return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
  };
  //3回到顶部
  function toTop(n) {
   $(window).on('scroll', function() {
    //console.log(getScrollTop()+"!"+getScrollHeight());
    if ($("#totop").size() > 0) {
     if (getScrollTop() < $(window).height() * n) {
      $("#totop").remove();
     }
    } else {
     if (getScrollTop() >= $(window).height() * n) {
      $("body").after("<div id='totop'>totop</div>");
      //插入了新标签 ,记得添加样式!
      $("#totop").on('click', function() {
       scroll(0,200);
      });
     }
    }
   });
  };
  //xxx.js文件来执行
  $(function(){
   toTop(2);
  })
 </script>
</html>

更多关于jQuery相关内容感兴趣的读者可查看本站专题:《jQuery窗口操作技巧总结》、《jQuery常用插件及用法总结》、《jquery中Ajax用法总结》、《jQuery表格(table)操作技巧汇总》、《jQuery扩展技巧总结》、《jQuery常见经典特效汇总》、《jQuery动画与特效用法总结》及《jquery选择器用法总结》

希望本文所述对大家jQuery程序设计有所帮助。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/5175.html