<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>选项卡</title>
<style type="text/css">
*{
padding: 0;
margin: 0;
}
ul{
list-style: none;
}
#tab{
width: 600px;
margin: 20px auto;
border: 1px solid red;
}
ul li{
display: block;
float: left;
width: 200px;
height: 60px;
line-height: 60px;
text-align: center;
background-color: #666666;
}
ul li a{
text-decoration: none;
color: black;
}
li.active{
background-color: #ffffff;
}
p{
display: none;
height: 300px;
text-align: center;
line-height: 300px;
background-color: #ffffff;
}
p.active{
display: block;
}
</style>
</head>
<body>
<div id="tab">
<ul>
<li class="active"><a href="#">首页</a> </li>
<li><a href="#">新闻</a> </li>
<li><a href="#">图片</a> </li>
</ul>
<p class="active">首页内容</p>
<p>新闻内容</p>
<p>图片内容</p>
</div>
</body>
<script type="text/javascript">
var tabcontent=document.getElementsByTagName("p");
var tabli=document.getElementsByTagName('li');
for(var i=0;i<tabli.length;i++){
// 给添加onclick事件时,应该保存当前点击的index值,即给添加一个index属性
tabli[i].index=i;
tabli[i].onclick=function () {
for(var j=0;j<tabli.length;j++){
tabli[j].className='';
tabcontent[j].className='';
}
this.className="active";
// console.log(this.index);
tabcontent[this.index].className="active";
}
}
</script>
</html>