Home > Web Front-end > JS Tutorial > body text

jQuery implements back to top function

php中世界最好的语言
Release: 2018-04-19 15:18:15
Original
1709 people have browsed it

This time I will bring you jQuery to implement the return to the top function. What are the precautions for jQuery to implement the return to the top function. The following is a practical case, let’s take a look.

<!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("<p id=&#39;totop&#39;>totop</p>");
      //插入了新标签 ,记得添加样式!
      $("#totop").on('click', function() {
       scroll(0,200);
      });
     }
    }
   });
  };
  //xxx.js文件来执行
  $(function(){
   toTop(2);
  })
 </script>
</html>
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:



The above is the detailed content of jQuery implements back to top function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template