回到顶部的js代码

<!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>回到顶部的js代码</title>
</head>
<style>
*{ margin:0; padding:0;}
body{ font:12px/1.6 Arial, Helvetica, sans-serif;}
.wrap{ height:2000px; margin:0 auto; width:800px; background:#F63; box-shadow:2px 2px 6px #000;}
#gotop{ position:fixed; right:10px; bottom:20px; background:#666; border-radius:5px; padding:10px 5px; color:#fff; text-shadow:1px 1px 2px #999; text-decoration:none; box-shadow:1px 1px 5px #fff inset;
_position:absolute;}
#gotop:hover{ background: #039;}
</style>
<body>
<script>
function $(id){
		return document.getElementById(id);
		}
window.onload=function(){
	var gotop=$("gotop");
	var isbool=true;
	var timer=null;
	//如何检测用户拖动了滚动条
	window.onscroll=function(){
		if(!isbool){
      clearInterval(timer);
			}
			isbool=false;
		}
	gotop.onclick=function(){
		
		timer=setInterval(function (){
			var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
			var iSpeed=Math.floor(-scrollTop/8); //设置滚动的速度
			
			if(scrollTop==0)
			{
				clearInterval(timer);
			}
			
			isbool=true;
			document.documentElement.scrollTop=document.body.scrollTop=scrollTop+iSpeed;
		}, 30);
		
		}
	}
	

</script>
	<div class="wrap">
         
    		
    </div>
    <a href="javascript:;" id="gotop">回到顶部</a>
    
</body>
</html>

在线预览地址:http://jsbin.com/uxiwuv/1

posted on 2013-05-19 16:54  仙梦之飘  阅读(287)  评论(0编辑  收藏  举报