AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > JavaScript

javascript实现回到顶部特效

51自学网 http://www.wanshiok.com
javascript,回到顶部

HTML:

<input id="btn1" type="button" value="回到顶部" />

CSS:

#btn1{position:fixed;bottom:10px;right:10px;}

JS:

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时需要清除定时器
3.需要判断是用户还是js操作滚动条,如果是用户操作就清除定时器

以上所述就是本文的全部内容了,希望大家能够喜欢。


javascript,回到顶部  
上一篇:js中日期的加减法  下一篇:javascript实现完美拖拽效果