<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css"> *{
padding:0;
margin:0;
}
.tab{
width: 300px;
height: 300px;
border:1px solid #333;
margin:50px auto;
}
.tab .hd{
height:40px;
line-height: 39px;
text-align: center;
overflow: hidden;
}
.tab .hd span{
float: left;
width: 99px;
height:39px;
border-left:1px solid #333;
border-bottom:1px solid #333;
}
.tab .hd span:first-child{
width: 100px;
border-left: none;
}
.tab .hd span.cur{
background-color: lightblue;
border-bottom: none;
font-weight: bold;
}
.tab .bd{
overflow: hidden;
}
.tab .bd div{
width: 100%;
height: 260px;
display: none;
}
.tab .bd div.cur{
display: block;
} </style>
</head>
<body>
<div class="tab">
<div class="hd" id="hd">
<span class="cur">新闻</span>
<span>体育</span>
<span>时尚</span>
</div>
<div class="bd" id="bd">
<div class="cur">新闻</div>
<div>体育</div>
<div>时尚</div>
</div>
</div> <script type="text/javascript">
// 获取元素
var spans = document.getElementById("hd").getElementsByTagName("span");
var divs = document.getElementById("bd").getElementsByTagName("div"); // 批量给span添加鼠标进入事件
for(var i = 0 ; i < spans.length ; i ++){
// 将i保存在index属性中
spans[i].index = i; spans[i].onmouseenter = function(){
// 所有的span恢复原状
for(var j = 0 ; j < spans.length ; j ++){
spans[j].className = "";
}
// 特殊的那个span加cur。
this.className = "cur"; // div对应和排他
// 所有div恢复原状
for(var k = 0 ; k < divs.length ; k ++){
divs[k].className = "";
}
// 对应的div加cur
divs[this.index].className = "cur";
};
} </script>
</body>
</html>