JavaScript 实现tab选项卡切换效果
CSS:
* {
padding: 0px;
margin: 0px;
box-sizing: border-box;
}
.main {
border: 1px solid #ccc;
width: 440px;
height: auto;
margin: 0 auto;
}
.top {
width: 440px;
height: 45px;
}
.top li {
float: left;
width: 110px;
height: 45px;
line-height: 45px;
list-style: none;
cursor: pointer;
text-align: center;
color: #333;
border-bottom: 1px solid #ccc;
}
.conent {
width: 440px;
height: 250px;
}
.conent div {
text-align: center;
font-size: 40px;
width: 440px;
height: 250px;
line-height: 200px;
color: skyblue;
}
.top .cur {
background-color: skyblue;
color: #fff;
}
#con .curent {
opacity: 1;
transition: all .8s ease;
}
#con div {
opacity: 0;
position: absolute;
}
HTML:
<div class="main">
<div class="top">
<ul id="top-2">
<li class="cur">选项一</li>
<li>选项二</li>
<li>选项三</li>
<li>选项四</li>
</ul>
</div>
<div class="conent" id="con">
<div class="curent">鹅,鹅,鹅,</div>
<div>曲项向天歌。</div>
<div>白毛浮绿水,</div>
<div>红掌拨清波。</div>
</div>
</div>
JS:
var top = document.getElementsByClassName('top');
var ul = document.getElementById('top-2');
var liobj = ul.getElementsByTagName('li');
var conent = document.getElementById('con');
var xx = conent.getElementsByTagName('div');
// console.log(liobj);
for(var i=0; i<liobj.length; i++){
// 给每个li设置自定义属性,记录索引值
liobj[i].setAttribute("data", i);
// 给每个li添加点击事件
liobj[i].onclick = function(){
// 先遍历,把每个li都删除class属性
for(var j=0; j<liobj.length; j++){
liobj[j].removeAttribute("class");
}
// 再把当前点击的li设置class属性
this.setAttribute("class", "cur");
// 下方内容切换
// 获取当前被点击的li的索引值
var num = this.getAttribute("data");
// 先遍历,把每个div都删除class属性
for(var k=0; k<xx.length; k++){
xx[k].removeAttribute("class");
}
// 再根据拿到的当前被点击的li的索引值设置 选项内容 div 的class属性
xx[num].setAttribute("class", "curent");
};
}
效果演示