JavaScript returns the top button implementation method _javascript tips

Source: Internet
Author: User

This article introduces JavaScript to return to the top of the button implementation method, shared for everyone to refer to, the specific content as follows

Html:

<a href= "javascript:;" id= "btn" title= "Back to Top" ></a>

Css:

#btn {position:fixed;display:none;}

Script

Get scroll bar height:document.documentElement.scrollTop | | document.body.scrollTop

Get the height of the visual area:document.documentElement.clientHeight
JS Code

 Window.onload = function () {var obtn = document.getElementById (' btn ');
  Gets the height of the page's visual region var clientheight = document.documentElement.clientHeight;
  var timer = null;
  var istop = true;
    Window.onscroll = function () {var ostop = Document.documentElement.scrollTop | | document.body.scrollTop;
    if (ostop >= clientheight) {//display button Obtn.style.display = ' block ';
    }else {//hidden button Obtn.style.display = ' None ';
    } if (!istop) {clearinterval (timer);
  } Istop = false;
  }; Obtn.onclick = function () {//Set timer timer = setinterval (function () {//Get the height of the scroll bar from the top of the var ostop = docu Ment.documentElement.scrollTop | |
      Document.body.scrollTop;
      var ispeed = Math.floor (-OSTOP/6);
      
      Document.documentElement.scrollTop = Document.body.scrollTop = Ostop +ispeed;
      Istop = true;
      if (Ostop = = 0) {clearinterval (timer);
  }},30);
}; 
};

Hopefully this article will help you learn about JavaScript programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.