1.html
<body>
<div class="box" id="box">
<ul class="nav" id="item">
<li class="bg_color"><a href="JavaScript: ;">百度</a></li>
<li><a href="JavaScript: ;">天猫</a></li>
<li><a href="JavaScript: ;">腾讯</a></li>
<li><a href="JavaScript: ;">新浪</a></li>
</ul>
<div class="bk">我是百度</div>
<div>我是天猫</div>
<div>我是腾讯</div>
<div>我是新浪</div>
</div>
</body>
2.css
*{
margin: 0;
padding: 0;
}
ul{
list-style: none;
}
a{
text-decoration: none;
}
.box{
width: 1000px;
height: 500px;
box-sizing: border-box;
border: 1px solid silver;
margin-left: auto;
margin-right: auto;
margin-top: 50px;
overflow: hidden;
}
.nav{
background: pink;
}
.nav:after{
content: "";
display: table;
clear: both;
}
.nav>li{
float: left;
line-height: 50px;
padding: 0 40px;
}
.nav>li>a{
color: white;
}
.nav>.bg_color{
background: orange;
}
.box>div{
height: 450px;
text-align: center;
line-height: 450px;
font-size: 50px;
display: none;
background: skyblue;
}
.box>.bk{
display: block;
}
3.js
var item = document.getElementById("item"); //得到头部item
var items = item.getElementsByTagName("li"); //得到头不所有的元素
var box = document.getElementById("box"); //得到内容box
var conts = box.getElementsByTagName("div"); //得到所有的内容列
for(var i = 0; i < items.length; i++) { //遍历所有的头部项
var ind = items[i]; //把i的值存起来
ind.index = i; //给每一个头部项添加index属性
items[i].onclick = function() { //点击某一个头部项
for(var j = 0; j < conts.length; j++) { //遍历所有的内容项
items[j].style.background = "transparent"; //把所有的头部项的颜色变为透明
this.style.background = "orange"; //给点击的这个头部项加上背景颜色
conts[j].style.display = "none"; //把所有的内容项设置为display:none
conts[this.index].style.display = "block"; //给点击对应的内容项设置为display:baock
}
}
}