<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>回到顶部效果</title><style> *{ margin:0;padding:0; } .box{ width:1190px; margin:0 auto; } .box img{ } #btn{ width:40px;height:40px;position:fixed; left:50%; bottom:30px;background:url(images/top_bg.png) no-repeat left top; margin-left:610px; } #btn:hover{ background:url(images/top_bg.png) no-repeat left -40px; width:40px;height:40px; }</style></head><body><script type="text/javascript"> window.onload=function(){ var btn=document.getElementById("btn"); var timer=null; var flag=true; window.onscroll=function(){ if(!flag){ clearInterval(timer); } flag=false; }; btn.onclick=function(){ timer=setInterval(function(){ var top=document.documentElement.scrollTop||document.body.scrollTop; var iSpeed=Math.floor(-top/8); document.documentElement.scrollTop=document.body.scrollTop=top+iSpeed; console.log(top+iSpeed); flag=true; if(top==0){ clearInterval(timer); } },30); } }</script> <div class="box"> <img src="images/tb_bg.jpg"> </div> <a href="javascript:;" id="btn"></a></body></html>
3 回答
ruibin
TA贡献358条经验 获得超213个赞
你看程序的执行顺序就行。当执行这里时
window.onscroll=function(){
if(!flag){
clearInterval(timer);
}
flag=false; //此处吧flag设置为false;
};
document.documentElement.scrollTop=document.body.scrollTop=top+iSpeed;
console.log(top+iSpeed);
flag=true;//此处把flag设置为true
if(top==0){
clearInterval(timer);
}
添加回答
举报
0/150
提交
取消