As JavaScript has become more and more widely used in recent years, and the sliding effect is everywhere, I have followed suit and made the stick function a slide effect. later, in order to better fit the physical characteristics, the sliding effect of deceleration was transformed.
Let's talk about the principle first. we will get the distance from the scroll bar to the top of the page, move up to a certain distance, and then get the distance from the scroll bar to the top of the page, move up a certain distance (a little smaller than the last time );...
JavaScript code:
Copy codeThe Code is as follows:
/**
* Return to the top of the page
* @ Param 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.doc umentElement ){
X1 = document.doc umentElement. scrollLeft | 0;
Y1 = document.doc umentElement. 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 the scroll bar to the top of the page
Var x = Math. max (x1, Math. max (x2, x3 ));
// Vertical distance from the scroll bar to the top of the page
Var y = Math. max (y1, Math. max (y2, y3 ));
// Rolling distance = current distance/speed, because the smaller the distance, the speed is greater than 1, so the rolling distance will be smaller and smaller
Var speed = 1 + acceleration;
Window. scrollTo (Math. floor (x/speed), Math. floor (y/speed ));
// If the distance is not zero, continue to call the iteration function.
If (x> 0 | y> 0 ){
Var invokeFunction = "goTop (" + acceleration + "," + time + ")";
Window. setTimeout (invokeFunction, time );
}
}
Document.doc umentElement. scrollTop, document. body. scrollTop, window. scrollY are actually the same, but they only play a role in some browsers. You can debug which browsers play a role.
HTML code:
Copy codeThe Code is as follows:
<A href = "#" onclick = "goTop (); return false;"> TOP </a>