トップに戻る効果

1931 ワード

慕授業ネット教程に基づく学習ノート
レイアウト
<!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" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
	<title>Javascript     </title>
	<style type="text/css">
		#btn {width:40px; height:40px; position:fixed; right:65px; bottom:10px; display:none; background:url(images/top_bg.png) no-repeat left top;}
		#btn:hover {
			
			background:url(images/top_bg.png) no-repeat 0 -39px;}
		.bg {width:1190px; margin:0 auto;}
	</style>
	
</head>
<body>
	<a href="javascript:;" id="btn" title="    "></a>
	<div class="bg">
		<img src="images/tb_bg.jpg" alt="" />
	</div>
</body>
</html>
Js
// JavaScript Document
window.onload=function(){
	var obtn=document.getElementById('btn');
	var timer=null;
	var isTop=true;
	var clientHeight=document.doucumentElement.clientHeight;//         
	
	//        
	window.onscroll=function(){
		var osTop=document.documentElement.scrollTop||doxument.body.scrollTop;//           
		if(ostop>=clientHeight){
		  obtn.style.display='block';	
		}else{
		  	obtn.style.display='none';
		}
		
		if(!isTop){
	    clearInterval(timer);	
		}
		istop=flase;
	}
	
	obtn.onclick=function(){
		//     
		timer=setInterval(function(){
			var osTop=document.documentElement.scrollTop||doxument.body.scrollTop;//           
		    var ispeed=Math.floor(-osTop/6);
			isTop=true;//             
			document.documentElement.scrollTop=document.body.scrollTop-=osTop+ispeed;
			if(osTop==0){
			   clearInterval(timer);	
			}
			},30);
		
	}
}