天天看點

jQuery實作回到頂部實作效果:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>回到頂部</title>

<script type="text/javascript" src="js/jquery-1.8.3.js"></script>

<script>
	
	// 當我們拖動視窗滾動條時,如果滾動條頂部偏移超過400,則顯示火箭,否則隐藏火箭(預設情況下火箭隐藏)
	$(window).scroll(function(){
		// 擷取視窗相對滾動條頂部的偏移
		var top = $(window).scrollTop();
		if(top > 400){// 當偏移量大于400,淡入火箭
			$(".rocketDv").fadeIn(500);
		} else{// 淡出火箭
			$(".rocketDv").fadeOut(500);
		}
		
	});
	
	// 給火箭添加點選事件
	$(function(){
		$(".rocketDv").click(function(){
			// 修改圖檔的路徑為 '帶噴火的火箭圖'
			$(".rocketDv>img").attr("src","images/gotoTop2.png");
			// 一秒内讓包裹火箭的div往上走,直到最頂部
			$(".rocketDv").stop().animate({"top":"0px"},1000,'linear',function(){
				// 火箭歸原位
				$(".rocketDv").hide().css({"top":"350px"});
				// 火箭圖檔變回最開始的圖檔
				$(".rocketDv>img").attr("src","images/gotoTop1.png");
				// 視窗滾動條回到最頂部
				$(window).scrollTop(0);
			});
			
		});
	});
	

</script>

<style>
	.rocketDv{
		width: 50px;
		height: 101px;
		position: fixed;
		top: 350px;
		right: 20px;
		display: none;
	}

</style>

</head>
<body>
	<!-- 設定高度:讓浏覽器視窗有滾動條 -->
	<div style="height: 1500px;"></div>
	<!-- 包裹火箭的div -->
	<div class="rocketDv">
		<img src="images/gotoTop1.png"/>
	</div>
	
</body>
</html>
           

實作效果:

jQuery實作回到頂部實作效果: