jq两行代码实现tab栏切换
主要思想:排它思想
所有元素全部清除样式(干掉其他人) 给当前元素设置样式(留下我自己)
完成效果如下:
html主要结构,添加了一个current类为当前的tab切换栏和内容栏,tab切换栏和内容栏结构大致相同,开始内容栏全部为隐藏只显示有current类的内容栏
<div class="hd">
<span>tab1</span>
<span class="current">tab2</span>
<span>tab3</span>
<span>tab4</span>
</div>
<div class="bd">
<ul id="list">
<li>我是tab1的内容模块</li>
<li class="current">我是tab2的内容模块</li>
<li id="li3">我是tab3的内容模块</li>
<li>我是tab4的内容模块</li>
</ul>
</div>
js代码:给tab栏添加点击事件,这里的$(this)为判断点击了哪一个tab栏,给该tab栏添加一个current类,给他的兄弟元素移除current类,这里的tab栏的内容和tab栏结构一致,即tab栏下标与内容栏的下标一致,可以通过下标显示对应的内容栏
$('#box>.hd>span').click(function () {
$(this).addClass('current').siblings().removeClass('current');
$('#list>li').removeClass('current').eq($(this).index()).addClass('current');
})
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="../jq_origin/jquery-1.12.4.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
ul {
list-style: none;
}
.box {
width: 400px;
height: 300px;
/* border: 1px solid #ccc; */
margin: 100px auto;
}
.hd {
display: flex;
height: 45px;
width: 400px;
}
.hd span {
flex: 1;
margin: 1px;
background-color: tomato;
line-height: 45px;
text-align: center;
cursor: pointer;
}
.hd span.current {
/*交集选择器,标签指定式选择器*/
background-color: skyblue;
}
.bd li {
height: 255px;
background-color: skyblue;
display: none;
/*设置隐藏*/
}
.bd li.current {
display: block;
/*显示*/
}
</style>
</head>
<body>
<div class="box" id="box">
<div class="hd">
<span>tab1</span>
<span class="current">tab2</span>
<span>tab3</span>
<span>tab4</span>
</div>
<div class="bd">
<ul id="list">
<li>我是tab1的内容模块</li>
<li class="current">我是tab2的内容模块</li>
<li id="li3">我是tab3的内容模块</li>
<li>我是tab4的内容模块</li>
</ul>
</div>
</div>
<script>
$('#box>.hd>span').click(function () {
$(this).addClass('current').siblings().removeClass('current');
$('#list>li').removeClass('current').eq($(this).index()).addClass('current');
})
</script>
</body>
</html>