Wrote two functions back to the top
One is this:
function fanhui() {varDistvarTimervarflag=true;varup_btn=Document. getElementById ("UP_BTN");varclientheight=Document. documentelement.clientheight;window. onscroll= function() {varheight=Document. documentelement.scrolltop| |Document. body.scrolltop;if(Height>=clientheight) {up_btn.style.display="Block"; }Else{up_btn.style.display="None"; }if(flag==false) {cleartimeout (timer); } flag=false; } up_btn.onclick= function() {Moveelement ( -); } function moveelement(interval) {varheight=Document. documentelement.scrolltop| |Document. body.scrolltop; dist=Math. ceil (height/Ten);Console. log (dist);Document. documentelement.scrolltop=Document. body.scrolltop-=dist;if((Document.documentelement.scrolltop>0)|| (Document.body.scrolltop>0) {Timer=settimeout ( function() {moveelement (interval); },interval); }Else{cleartimeout (timer); } flag=true; }} Fanhui ()
The other one is like this.
function fanhui() {varbtn=Document. getElementById ("UP_BTN");varTimer=NULL;varflag=true;varclientheight=Document. documentelement.clientheight;window. onscroll= function() {varheight=Document. documentelement.scrolltop| |Document. body.scrolltop;if(Height>=clientheight) {btn.style.display="Block"; }Else{btn.style.display="None"; }if(flag==false) {clearinterval (timer); } flag=false; } btn.onclick= function() {Timer=setinterval ( function() {varheight=Document. documentelement.scrolltop| |Document. body.scrolltop;varIspeed=Math. ceil (height/Ten);Console. log (Ispeed);Document. documentelement.scrolltop=Document. body.scrolltop-=ispeed; flag=true;if(height==0) {clearinterval (timer); } }, -)}} Fanhui (); })
The desired result, first, is to achieve the top effect, and the smaller the distance from the top, the slower it moves. Second, it can be achieved in the process of upward sliding, if moving the wheel will end the effect of sliding.
Math.ceil () performs an upward rounding, that is, it always rounds the value up to the nearest integer.
The second sliding function: The main is to set a setinterval function so that it can be executed every 30 milliseconds, each time to get the height of the scroll, and then take the height of one-tenth as the distance of each upward slide, when the height is 0, clear the setinterval function. We can see the speed change every time we output speed in the console.
The first sliding function is to make a recursive call, first to get the height of the scrollbar scroll, and then to determine the height, if height>0, then 30 milliseconds after the execution of the sliding function, so loop, until the height of 0 jumps out of the function, recursion ends. It is important to note that recursive calling functions do not forget to pass parameters.
Practice has shown that the two functions perform the same thing.
Analysis of two animation functions