JavaScript实现tab选项卡效果
css代码
<style>
*{
margin: 0;
padding: 0;
}
.container{
width: 500px;
/*height: 700px;*/
border: 1px solid #000;
margin: 100px auto;
}
.container>ul{
background-color: skyblue;
list-style: none;
display: flex;
justify-content: space-between;
width: 100%;
height: 60px;
line-height: 60px;
}
ul>li{
width: 100px;
font-size: 20px;
border-right: 1px solid #000000;
text-align: center;
cursor: default;
}
ul>li:last-child{
border-right: none;
}
.content{
width: 100%;
height: 300px;
}
.bottom>.content:nth-child(1){
background-color: pink;
}
.bottom>.content:nth-child(2){
background-color: purple;
display: none;
}
.bottom>.content:nth-child(3){
background-color: greenyellow;
display: none;
}
.bottom>.content:nth-child(4){
background-color: orange;
display: none;
}
.bottom>.content:nth-child(5){
background-color: darkcyan;
display: none;
}
.current{
background-color: brown;
}
</style>
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>tab选项卡</title>
</head>
<body>
<div class="container">
<ul>
<li class="current">新闻</li>
<li>科技</li>
<li>数码</li>
<li>游戏</li>
<li>搞笑</li>
</ul>
<div class="bottom">
<div class="content">新闻内容</div>
<div class="content">科技内容</div>
<div class="content">数码内容</div>
<div class="content">游戏内容</div>
<div class="content">搞笑内容</div>
</div>
</div>
</body>
</html>
JavaScript代码
<script>
// 拿到所有的选项卡
let items = document.querySelectorAll("li");
// 拿到所有的内容
let contents = document.querySelectorAll(".content");
// 上一次选中的选项卡的索引
let preIndex = 0;
// 为所有选项卡添加单机响应事件
for (let i = 0; i < items.length; i++) {
items[i].onclick = function () {
items[preIndex].className = "";
contents[preIndex].style.display = "none";
items[i].className = "current";
contents[i].style.display = "block";
preIndex = i;
};
}
</script>
运行效果
作者:陈太浪
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。