<ul class="tabs">
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ul>
<div class="boxs">
<div class="tabs-box boxOne">1</div>
<div class="tabs-box">2</div>
<div class="tabs-box">3</div>
</div>
样式部分:
* {
margin: 0;
padding: 0;
}
.tabs {
display: flex;
}
.tabs li {
width: 100px;
height: 50px;
text-decoration: none;
list-style-type: none;
border: 1px solid #ccc;
margin-left: 10px;
}
.tabs-box {
width: 330px;
background-color: burlywood;
height: 100px;
display: none
}
.active {
background-color: steelblue;
color: #fff;
}
.boxOne {
display: block;
}
// eq()方法:返回被选元素中带有指定索引号的元素。
$('.tabs li').on('click', function () {
// 给当前选中的li添加一个选中的样式,除了点击当前的这个样式其他的删除样式
$(this).addClass('active').siblings().removeClass('active');
// 第一种写法
// $('.boxs > div').hide().eq($('.tabs li').index(this)).show();
// 第二种写法
// siblings:除自己以外
// 当前指向的上级父元素的下一个子元素的索引下标出现,让其他的消失
$(this).parent().next().children().eq($(this).index()).css('display', 'block').siblings().css('display', 'none');
})
效果如下:
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tab栏</title>
<script src="./js/jquery-3.5.1.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
.tabs {
display: flex;
}
.tabs li {
width: 100px;
height: 50px;
text-decoration: none;
list-style-type: none;
border: 1px solid #ccc;
margin-left: 10px;
}
.tabs-box {
width: 330px;
background-color: burlywood;
height: 100px;
display: none
}
.active {
background-color: steelblue;
color: #fff;
}
.boxOne {
display: block;
}
</style>
</head>
<body>
<ul class="tabs">
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ul>
<div class="boxs">
<div class="tabs-box boxOne">1</div>
<div class="tabs-box">2</div>
<div class="tabs-box">3</div>
</div>
<script>
// eq()方法:返回被选元素中带有指定索引号的元素。
$('.tabs li').on('click', function () {
// 给当前选中的li添加一个选中的样式,除了点击当前的这个样式其他的删除样式
$(this).addClass('active').siblings().removeClass('active');
// 第一种写法
// $('.boxs > div').hide().eq($('.tabs li').index(this)).show();
// 第二种写法
// siblings:除自己以外
// 当前指向的上级父元素的下一个子元素的索引下标出现,让其他的消失
$(this).parent().next().children().eq($(this).index()).css('display', 'block').siblings().css('display', 'none');
})
</script>
</body>
</html>
更多推荐