下面来讲说最近学习到的回到顶部特效:html
<input id="btn1" type="button" value="回到顶部" />
#btn1{position:fixed;bottom:10px;right:10px;}
window.onload=funcition(){ var oBtn=document.getElementById("btn"); var timer=null; //申明一个变量看是否为系统仍是用户滚动 var sBys=true; window.onscroll=funcition(){ if(!sBys){ clearInterval(timer); } sBys=false; } oBtn.onclick=funcition(){ timer = setInterval(funcition(){ //获取scrollTop var scrollTop=document.documentElement.scrollTop||document.body.scrollTop; //当点击按钮回到顶部时计算缓冲速度 var ispeed=Math.floor(-scrollTop/8); if(scrollTop==0){ clearInterval(timer) } sBys=true; document.documentElement.scrollTop=document.body.scrollTop=scrollTop+ispeed; },30) } }
知识点:1.计算速度(缓冲)向下取整学习
2.当scrollTop==0时须要清除定时器
spa
3.须要判断是用户仍是js操做滚动条,若是是用户操做就清除定时器
code