js simply clicks back to the top effect implementation

  • 2020-05-27 04:12:13
  • OfStack

This article illustrates the simple click back to top effect implementation of js. Share with you for your reference. The specific analysis is as follows:

When the page is very long, users want to return to the top of the page, must scroll the scroll key several times to return to the top, if there is a "back to the top" button in the bottom right corner of the page, users click 1, you can return to the top, for users, is a good experience.

How it works: when the page loads, position the element to the bottom right corner of the page. When the page scrolls, the element 1 sits in the bottom right corner. When the user clicks, the page goes back to the top.

Point 1: document.documentElement.clientWidth || document.body.clientWidth; Gets the width of the visible area. chrome in the back and other browsers in the front.

Point 2: oTop. style. left = screenw-oTop. offsetWidth +"px"; When the page loads, position the element to the far right of the page, subtracting the width of the element itself from the width of the viewable area.

Point 3: oTop.style.top = screenh-oTop.offsetHeight + scrolltop +"px"; As the page scrolls, the Y position of the element is equal to the height of the viewport minus the height of the element itself, plus the scrolling distance.

Point 4: document.documentElement.scrollTop = document.body.scrollTop =0; When clicking on an element, make the page scroll 0. Write both for compatibility.

The code:


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title> Headless document </title>
<style>
body{margin:0; padding:0}
#to_top{width:30px; height:40px; padding:20px; font:14px/20px arial; text-align:center; background:#06c; position:absolute; cursor:pointer; color:#fff}
</style>
<script>
window.onload = function(){
 var oTop = document.getElementById("to_top");
 var screenw = document.documentElement.clientWidth || document.body.clientWidth;
 var screenh = document.documentElement.clientHeight || document.body.clientHeight;
 oTop.style.left = screenw - oTop.offsetWidth +"px";
 oTop.style.top = screenh - oTop.offsetHeight + "px";
 window.onscroll = function(){
  var scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
  oTop.style.top = screenh - oTop.offsetHeight + scrolltop +"px";
 }
 oTop.onclick = function(){
  document.documentElement.scrollTop = document.body.scrollTop =0;
 }
} 
</script>
</head>
<body style="height:1000px;">
<h1> Return to the top </h1>
<div id="to_top"> Return to the top </div>
</body>
</html>

I hope this article is helpful for you to design javascript program.


Related articles: