1. 程式人生 > >前端 閉包做選項卡

前端 閉包做選項卡

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>閉包做選項卡</title>
	<style type="text/css">
		.btns{
			width: 500px;
			height: 50px;
		}
		/*選項卡的樣式*/
		.btns input{
			width: 100px;
			height: 50px;
			background-color: #ddd;/*預設灰色*/
			color: #666;
			border: 0px;
		}
		/*被選中的選項卡的樣式*/
		.btns input.cur{
			background-color: gold;
		}
		/*內容區的樣式*/
		.contents div{
			width: 500px;
			height: 300px;
			background-color: gold;
			display: none;/*預設隱藏*/
			line-height: 300px;
			text-align: center;
		}
		/*被選中的內容區的樣式*/
		.contents div.active{
			display: block;
		}
	</style>
	<script type="text/javascript">
		//閉包做選項卡
		window.onload = function(){
			var aBtn = document.getElementById('btns').getElementsByTagName('input');
			var aCon = document.getElementById('contents').getElementsByTagName('div');
			// alert(aCon.length);

			//迴圈所有的選項卡按鈕
			for(var i=0; i<aBtn.length; i++){
				(function(i){
					//給每個選項卡按鈕新增點選事件
					aBtn[i].onclick = function(){
						//遍歷所有選項卡按鈕
						for(var j=0; j<aBtn.length; j++){
							//將每個選項卡按鈕都設為灰色
							aBtn[j].className = '';
							//將每個內容區都隱藏
							aCon[j].className = '';
						}
						//this代表當前點選的Button物件
						this.className = 'cur';//當前點選的按鈕為金色

						// alert(i);//不加閉包時,不管點哪個按鈕,i都等於3

						//加閉包儲存了索引值才有效
						aCon[i].className = 'active';//當前點選的按鈕對應的內容顯示
					}
				})(i);
			}
		}
	</script>
</head>
<body>
	<div class="btns" id="btns">
		<input type="button" value="tab01" class="cur">
		<input type="button" value="tab02">
		<input type="button" value="tab03">
	</div>
	<div class="contents" id="contents">
		<div class="active">tab文字內容一</div>
		<div>tab文字內容二</div>
		<div>tab文字內容三</div>
	</div>
</body>
</html>