Many pages will have a "back to the Top" button below, especially if there is no navigation at the bottom of the page, which will help visitors to find the navigation or revisit the ad (really beautiful). With the application of JavaScript in recent years more and more extensive, sliding effect everywhere, so I also follow the bandwagon, will return to the top function made a sliding effect. Later, in order to better fit the physical characteristics of the transformation made a deceleration sliding effect.
First of all, we will get the scroll bar to the top of the page distance, and then move up a certain distance, and then get the scroll bar to the top of the page distance, up a certain distance (smaller than the previous one);
Copy Code code as follows:
<script type= "Text/javascript" >
/**
* Back to the top of the page
* @param acceleration acceleration
* @param time interval (ms)
**/
function gotop (acceleration, time) {
Acceleration = Acceleration | | 0.1;
Time = Time | | 16;
var x1 = 0;
var y1 = 0;
var x2 = 0;
var y2 = 0;
var x3 = 0;
var y3 = 0;
if (document.documentelement) {
X1 = Document.documentElement.scrollLeft | | 0;
Y1 = Document.documentElement.scrollTop | | 0;
}
if (document.body) {
x2 = Document.body.scrollLeft | | 0;
y2 = Document.body.scrollTop | | 0;
}
var x3 = Window.scrollx | | 0;
var y3 = window.scrolly | | 0;
Horizontal distance from scroll bar to top of page
var x = Math.max (x1, Math.max (x2, x3));
The vertical distance from the scroll bar to the top of the page
var y = Math.max (y1, Math.max (y2, y3));
Scrolling distance = current distance/speed, because the smaller the distance, the speed is greater than 1 of the number, so the rolling distance will be less and less
var speed = 1 + acceleration;
Window.scrollto (Math.floor (x/speed), Math.floor (Y/speed));
If the distance is not zero, continue calling the iterative function
if (x > 0 | | | y > 0) {
var invokefunction = "Gotop (" + Acceleration + "," + Time + ")";
Window.settimeout (invokefunction, time);
}
}
</script>
Document.documentElement.scrollTop, Document.body.scrollTop, window.scrolly are all the same, but they only work in some browsers. As for which browsers work, you can debug yourself.
How to use it?
Copy Code code as follows:
<a href= "#" onclick= "Gotop (); return false;" >TOP</a>