<!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=gb2312" />
<title>js实现回到顶部</title>
</head>
<style type="text/css">
.box{ width:1190px; margin:0 auto;}
#btn{ width:40px; height:40px; margin-left:610px; bottom:30px; left:50% ;position:fixed; background:url(top_bg.png) no-repeat left top; display:none;}
#btn:hover{ background:url(top_bg.png); background-position:0 -40px;}
</style>
<script type="text/javascript">
window.onload=function(){//页面加载完成后执行
var obtn=document.getElementById("btn");
var timer=null;
var my_scroll=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(!my_scroll){
clearInterval(timer);
}
my_scroll=false;
}
obtn.onclick=function(){
var timer=setInterval(function(){//定时器
//滚动条距离页面顶端的距离
var osTop=document.documentElement.scrollTop||document.body.scrollTop;
var ispeed=Math.floor(-osTop/6);//向下取整
my_scroll=true;
document.documentElement.scrollTop=document.body.scrollTop=osTop+ispeed;//滚轮回到顶部由快到慢
if(osTop==0){
clearInterval(timer);
}
},30);
}
}
</script>
<body>
<div class="box"><img src="tb_bg.jpg" /></div>
<a href="javascript:;" id="btn" title="回到顶部"></a><!--javascript:;阻止标签的默认行为-->
</body>
</html>