当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jQuery实现简单的回到顶部totop功能示例

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网