Javascript实现简单的选项卡

时间:2021-05-01 06:26:31

在线演示:http://jsfiddle.net/Web_Code/TbPDd/embedded/result/

<!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">
<head>
	<meta http-equiv="content-type" content="texthtml;charset=utf-8">
	<title>TabHost</title>
	<style type="text/css">	
		 #tab li
		{
			background-color: #3e3e3e;
			list-style: none;
			float: left;
			margin-left: 2px;
			color: white;
		}
		#tabContent
		{
			float: left;
			display: none;
			width: 242px;
			height: 150px;
		}
		#tabContent ul
		{
			list-style: none;
			background-color: #ccc;
			padding-left: 5px;
			margin-top: 0px;
		}
		#main
		{
			width: 250px;
			margin: 0 auto;
			height: 300px;
		}
	</style>
</head>
<body>
	<div id="main">
		<div style="margin-left:-42px">
			<ul id="tab">
				<li onclick="javascript:display(1);" style="background-color:#ccc;color:black;">
				数 据 库
				</li>
				<li onclick="javascript:display(2);">
				前台脚本
				</li>
				<li onclick="javascript:display(3);">
				后台脚本
				</li>
			</ul>
		</div>
		<div id="tabContent" style="display:block">
			<ul>
				<li>MySql</li>
				<li>SQL Server</li>
				<li>Oracle</li>
				<li>DB2</li>
			</ul>
		</div>
		<div id="tabContent">
			<ul>
				<li>HTML</li>
				<li>Ruby</li>
				<li>JavaScript</li>
				<li>Python</li>
			</ul>
		</div>
		<div id="tabContent">
			<ul>
				<li>ASP</li>
				<li>PHP</li>
				<li>.Net</li>
				<li>JSP</li>
			</ul>
		</div>
	</div>
	<script type="text/javascript">
		var divs = document.getElementById("main").getElementsByTagName("div");
		var lis = document.getElementById("tab").getElementsByTagName("li");
		function display(num)
		{
			for(var i = 1; i < divs.length; i++)
			{
				if(i == num)
				{
					var con = divs[num];
					con.style.display="block";
					lis[i-1].style.backgroundColor = "#ccc";
					lis[i-1].style.color = "black";
				}
				else
				{
					divs[i].style.display = "none";
					lis[i-1].style.color = "white";
					lis[i-1].style.backgroundColor = "#3e3e3e";
				}
			}
		}
	</script>
</body>
</html>