javascript implements back to top effects
- 2020-06-03 05:53:16
- OfStack
HTML:
<input id="btn1" type="button" value=" Back to the top " />
CSS:
#btn1{position:fixed;bottom:10px;right:10px;}
JS:
window.onload=funcition(){
var oBtn=document.getElementById("btn");
var timer=null;
// statement 1 Three variables to see whether the system or the user scrolls
var sBys=true;
window.onscroll=funcition(){
if(!sBys){
clearInterval(timer);
}
sBys=false;
}
oBtn.onclick=funcition(){
timer = setInterval(funcition(){
// To obtain scrollTop
var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
// Calculate the buffering speed when the button is clicked back to the top
var ispeed=Math.floor(-scrollTop/8);
if(scrollTop==0){
clearInterval(timer)
}
sBys=true;
document.documentElement.scrollTop=document.body.scrollTop=scrollTop+ispeed;
},30)
}
}
Knowledge:
1. Calculate speed (buffer) and round down
2. Clear the timer when scrollTop==0
3. Need to determine whether it is user or js operation scroll bar, if it is user operation, clear the timer
This is the end of this article, I hope you enjoy it.