回到顶部效果

CSS:

width:40px;
height:40px;
position:fixed;
left:50%;
display:none;
margin-left:页面宽度/2;
bottom:30px;

JavaScript:

window.onload=function(){
var obtn = document.getElementById('btn');

//获取页面可视区的高度
var clientHeight = document.documentElement.clientHeight;
var timer = null;
var isTop = true;
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 speed=Math.ceil(osTop/6);//向上取整,最后至少为1
document.documentElement.scrollTop = document.body.scrollTop = osTop -speed;
isTop=true;
if (osTop===0){
clearInterval(timer);
};
},30);
};
};

 

posted @ 2016-01-17 13:25  inethard  阅读(128)  评论(0编辑  收藏  举报