一个很简易的利用事件委托addEventListener实现的tab的点击切换功能:::::
HTML结构代码:
<ul id="ul">
<li>首页</li>
<li>关于</li>
<li>我的</li>
<li>联系</li>
</ul>
<div id="content">
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
<div id="div4">div4</div>
</div>
CSS样式代码:
<style type="text/css">
*{
margin: 0;padding: 0;
}
ul li{
list-style: none;
float: left;
padding: 10px 45px;
background: greenyellow;
cursor: pointer;
}
#ul:after{
content: ".";
clear: both;
visibility: hidden;
width: 0;height: 0;
}
.cilckColor{
background: green;
}
#content div{
width: 500px;
height: 300px;
}
#div1{
background: yellow;
}
#div2{
background: cyan;
display: none;
}
#div3{
background: gold;
display: none;
}
#div4{
background: blueviolet;
display: none;
}
</style>
JS行为代码:
<script type="text/javascript">
var ul=document.getElementById("ul");
var li=ul.getElementsByTagName("li");
var div=document.getElementById("content");
var divChild=div.getElementsByTagName("div");
//var mark=0;
function change(index){
for(var i = 0; i<li.length; i++){
li[i].className="";
divChild[i].style.display="none";
}
li[index].className="cilckColor";
divChild[index].style.display="block";
//mark=index;
}
ul.addEventListener("click",function(){
for(var i=0;i<li.length;i++){
li[i].index=i;
li[i].addEventListener('click',function(){
change(this.index);
});
}
},true); // 这里不给true的话,得点击导航两下才能给加上背景色
</script>