天翼翱翔
2017-04-16 11:08:01
<!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貢獻(xiàn)358條經(jīng)驗 獲得超213個贊
你看程序的執(zhí)行順序就行。當(dāng)執(zhí)行這里時
?window.onscroll=function(){
? ? ? ? ? if(!flag){
? ? ? ? ? ? ? clearInterval(timer);
? ? ? ? ? }
? ? ? ? ? flag=false; //此處吧flag設(shè)置為false;
? ? ? };
document.documentElement.scrollTop=document.body.scrollTop=top+iSpeed;
? ? ? ? ? ? ? ?console.log(top+iSpeed);
? ? ? ? ? ? ? ?flag=true;//此處把flag設(shè)置為true
? ? ? ? ? ? ? ?if(top==0){
? ? ? ? ? ? ? ? ? ?clearInterval(timer);
? ? ? ? ? ? ? ?}
添加回答
舉報
0/150
提交
取消