一、實(shí)現(xiàn)原理
1、主要運(yùn)用“排他思想”,在設(shè)置當(dāng)前元素前,先把相應(yīng)元素恢復(fù)到默認(rèn)狀態(tài)
2、給相應(yīng)元素添加下標(biāo)的應(yīng)用
二、代碼展示
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
*{margin: 0;padding: 0;}
ul,li{ list-style: none; }
ul{display: block;overflow: hidden; clear: both;}
li{display:block;float: left; width: 200px; height: 40px;line-height: 40px; text-align: center; background:#eee; color: #333;cursor: pointer;}
li.on{ background:orange; color: #fff;}
div{width:600px;display: none; height: 400px; text-align: center;line-height: 400px; border:1px solid #eee; box-sizing: border-box;}
</style>
</head>
<body>
<ul id="box">
<li class="on">國(guó)內(nèi)</li>
<li>國(guó)外</li>
<li>市政</li>
</ul>
<div style="display: block;">國(guó)內(nèi)</div>
<div>國(guó)外</div>
<div>市政</div>
</body>
<script type="text/javascript">
var oLis = document.getElementsByTagName('li');
var oDiv = document.getElementsByTagName('div');
for (var i = 0; i < oLis.length; i++) {
//給每個(gè)li設(shè)置下標(biāo)
oLis[i].index = i;
oLis[i].onclick = function(){
//li點(diǎn)擊時(shí),拍他思想,把所有的li去掉選中狀態(tài),所有的div都隱藏
for (var j = 0; j < oLis.length; j++) {
oLis[j].className = '';
oDiv[j].style.display = 'none';
}
// 設(shè)置當(dāng)前點(diǎn)擊的li為選中狀態(tài)
this.className = 'on';
// 根據(jù)當(dāng)前l(fā)i的下標(biāo),設(shè)置對(duì)應(yīng)的div展示出來(lái)
oDiv[this.index].style.display = 'block';
}
}
</script>
</html>