Many pages have a "back to top" button underneath, especially one that doesn't have navigation at the bottom of the page, which can help visitors navigate again or revisit the ad (think it's beautiful). With the increasing use of JavaScript in recent years, the sliding effect is everywhere, so I also follow the following, will return to the top of the function made of sliding effect. Later, in order to better fit the physical characteristics, the transformation made a deceleration of the sliding effect.
First, let's say the principle, 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, move up a certain distance (smaller than the previous);
First, the code: Ruyang County First High School
View Source print?
01 |
<script type= "text/javascript" > |
04 |
* @param acceleration 加速度 |
05 |
* @param time 时间间隔 (毫秒) |
07 |
function goTop(acceleration, time) { |
08 |
acceleration = acceleration || 0.1; |
18 |
if (document.documentElement) { |
19 |
x1 = document.documentElement.scrollLeft || 0; |
20 |
y1 = document.documentElement.scrollTop || 0; |
23 |
x2 = document.body.scrollLeft || 0; |
24 |
y2 = document.body.scrollTop || 0; |
26 |
var x3 = window.scrollX || 0; |
27 |
var y3 = window.scrollY || 0; |
30 |
var x = Math.max(x1, Math.max(x2, x3)); |
32 |
var y = Math.max(y1, Math.max(y2, y3)); |
34 |
// 滚动距离 = 目前距离 / 速度, 因为距离原来越小, 速度是大于 1 的数, 所以滚动距离会越来越小 |
35 |
var speed = 1 + acceleration; |
36 |
window.scrollTo(Math.floor(x / speed), Math.floor(y / speed)); |
40 |
var invokeFunction = "goTop(" + acceleration + ", " + time + ")" ; |
41 |
window.setTimeout(invokeFunction, time); |
Effect demo back to top
Document.documentElement.scrollTop, Document.body.scrollTop, window.scrolly are actually the same, but they only work in some browsers. As for that which in which browser functions can debug itself.
How to use?
View Source print?
1 |
<a href= "#" onclick= "goTop();return false;" >TOP</a> |
Make a simple return to the top with native JavaScript