每天一个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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值