选项卡有多种多样的方法,今天献上一个原生js版本的选项卡,每行都会有注释,算是整理的笔记,如果有使用的可以直接拿走!
布局:
<div id="box">
<ul>
<li class="dk">达康</li>
<li>育梁</li>
<li>同伟</li>
<li>亮平</li>
<li>东来</li>
</ul>
<ol>
<li class="oy">你是不是特希望我下台啊</li>
<li>热情、礼貌、一问三不知</li>
<li>当好你的东宫正室</li>
<li>不能突破纪律的底线</li>
<li>当断则断</li>
</ol>
</div>
样式:
<style>
html,body,ul,li,ol{
margin: 0;
padding: 0;
list-style: none; /*去除ol、ul、li的小圆点*/
}
#box{
width: 600px;
height: 500px;
margin: 100px auto;
border: 1px solid;
}
#box>ul{
width: 100%;
height: 50px;
line-height: 50px;
border-bottom: 1px solid;
}
#box>ul>li{
width: 118px;
float: left; /*左浮动*/
text-align: center;
border-right: 1px solid;
}
#box>ul>li.dk{
background: lawngreen;
color: #ffffff;
}
#box>ol{
width: 100%;
height: 300px;
}
#box>ol>li{
width: 120px;
display: none; /*隐藏*/
float: left; /*左浮动*/
}
#box>ol>li.oy{
width: 600px;
display: block; /*显示*/
}
</style>
js逻辑代码:
<script>
// 获取ul
var oU = document.getElementsByTagName('ul')[0];
// 获取ul的子元素li
var oUl = oU.children;
// 获取ol
var oO = document.getElementsByTagName('ol')[0];
// 获取ol的子元素li
var oOl = oO.children;
// 循环每一个ul的li
for(var i = 0; i < oUl.length; i++){
// i重新赋值给Ul的子元素每一个li下标;
oUl[i].index = i;
// 给每一个li绑定事件
oUl[i].onclick = function(){
// 循环每一个ul的li
for(var j = 0; j < oUl.length; j++){
// 给每一个ul、ol下点击的li清除样式
oUl[j].className = '';
oOl[j].className = '';
}
// 给每一个ul、ol下点击的li添加样式
oUl[this.index].className = 'dk';
oOl[this.index].className = 'oy'
}
}
</script>