首页 > 代码库 > 每天一个JavaScript实例-tab标签切换

每天一个JavaScript实例-tab标签切换

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>每天一个JavaScript实例-tab标签切换</title>
<style>
	.tabcontainer{
		padding:5px;
		width:500px;
		margin:20px;
	}
	.tabcontainer ul{
		padding:0;
		margin:0;
		display:none;
	}
	.tabnavigation ul li{
		padding:3px;
		display: inline;
		border:1px solid #000;
		background-color:#fff;
	}
	.tabnavigation ul li:hover{
		cursor:pointer;
	}
	.tabpages{
		position:relative;
		z-index: 2;
		border:1px solid #000;
		background-color:#fff;
	}
	.tabpage{
		margin:0 10px;
	}
</style>

<script>
window.onload = function(){
	var containers = document.querySelectorAll(".tabcontainer");
	//console.log(containers);
	for(var j = 0;j<containers.length;j++){
		var nav = containers[j].querySelector(".tabnavigation ul");
		nav.style.display = "block";
		var navitem = containers[j].querySelector(".tabnavigation ul li");
		var ident  = navitem.id.split("_")[1];
		
		navitem.parentNode.setAttribute("data-current",ident);
		navitem.setAttribute("style","background-color:#f00;");

		var pages = containers[j].querySelectorAll(".tabpage");
		//console.log(pages);
		for(var i = 0; i < pages.length;i++){
			pages[i].style.display = "none";
		}
		var tabs = containers[j].querySelectorAll(".tabnavigation ul li");
		//console.log(tabs);
		for (var i = 0; i < tabs.length; i++) {
			tabs[i].onclick = displayPage;
		};
	}

}
function displayPage(){
	var current = this.parentNode.getAttribute("data-current");
	console.log(current);
	document.getElementById("tabnav_"+current).setAttribute("style","background-color:#fff");
	document.getElementById("tabpage_"+current).style.display="none";

	var ident = this.id.split("_")[1];
	//console.log(ident);
	this.setAttribute("style","background-color:#f00");
	document.getElementById("tabpage_"+ident).style.display = "block";
	this.parentNode.setAttribute("data-current",ident);
}
</script>

</head>

<body>

<div class = "tabcontainer">
	<div class="tabnavigation">
		<ul>
			<li id="tabnav_1">页面1</li>
			<li id="tabnav_2">页面2</li>
			<li id="tabnav_3">页面3</li>
		</ul>
	</div>

	<div class="tabpages">
		<div class="tabpage" id="tabpage_1">
			<p>页面1</p>
		</div>
		<div class="tabpage" id="tabpage_2">
			<p>页面2</p>
		</div>
		<div class="tabpage" id="tabpage_3">
			<p>页面3</p>
		</div>
	</div>
</div>
<div class="tabcontainer">
	<div class="tabnavigation">
		<ul>
			<li id="tabnav_4">页面2—1</li>
			<li id="tabnav_5">页面2—2</li>
		</ul>
	</div>
	<div class="tabpages">
		<div class="tabpage" id="tabpage_4">
			<p>页面4</p>
		</div>
		<div class="tabpage" id="tabpage_5">
			<p>页面5</p>
		</div>
	</div>
</div>
</body>
</html>

每天一个JavaScript实例-tab标签切换