回到顶部代码
<script type="text/javascript">
window.onload=function(){
var obtn=document.getElementById("btn");
var timer=null;
var isTop=true;
var clientHeight=document.documentElement.clientHeight;
window.onscroll=function() {//滚动条滚动时触发
var osTop=document.documentElement.scrollTop||document.body.scrollTop;
if(osTop>=clientHeight){
obtn.style.display="block";
}
else{
obtn.style.display="none";
}
if(!isTop){
clearInterval(timer);
}
isTop=false;
};
obtn.onclick=function(){
timer=setInterval(function(){//设置定时器
var osTop=document.documentElement.scrollTop||document.body.scrollTop;
var sped=Math.floor( -osTop / 5);
document.documentElement.scrollTop=document.body.scrollTop =osTop+sped;
isTop=true;
if(osTop==0){
clearInterval(timer);
}
},30);
}
}
</script>