Many web pages will place a "Back to Top" button below, especially web pages that do not have navigation at the bottom of the page, which can help visitors find navigation again or revisit the ad (it's so beautiful). As JavaScript is becoming more and more widely used in recent years, the sliding effect is everywhere, so I followed the trend and made the return to the top function to create a sliding effect. Later, in order to better fit the physical characteristics, the sliding effect of slowing down was transformed.
Let’s talk about the principle first. We will get the distance from the scroll bar to the top of the page, and then move it up by a certain distance; then get the distance from the scroll bar to the top of the page, and move it up by a certain distance (a little smaller than the last time); and so on...
<script type="text/javascript"> /** * Back to the top of the page* @param acceleration Acceleration* @param time 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 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)); // Scroll distance = Current distance/speed, Because the distance is smaller and the speed is greater than 1, the scrolling distance will become 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); } } </script>document.documentElement.scrollTop, document.body.scrollTop, window.scrollY are actually the same, but they only work in some browsers. As for which browsers work, you can debug it yourself.
How to use it?
The code copy is as follows:
<a href="#" onclick="goTop();return false;">TOP</a>