原生js实现tab切换 与 jq实现tab切换
原生js实现
**css部分**
<style>
*{
margin: 0;
padding: 0;
}
.warp{
width: 100%;
background-color: cyan;
display: flex;
}
.top{
width: 80vh;
height: 50px;
margin-left: 350px;
display: flex;
}
.top div{
background-color: cadetblue;
width: 100vh;
height:50px;
line-height: 50px;
text-align: center;
border-right: solid black 1px;
flex-direction: row;
}
h1{
text-align: center;
}
.top .active{
display: block;
background-color: yellowgreen;
color: white;
}
.bottom{
flex: 1;
/* background-color: palegoldenrod; */
}
.bottom>div{
display: none;
text-align: center;
}
.bottom .show{
display: block;
}
table{
width: 100vh;
border-collapse: collapse;
cursor: pointer;
margin: 0 auto;
}
table td{
text-align: center;
}
</style>
<div class="wrap">
<h1>垃圾分类</h1>
<div class="top">
<div class="active">生活垃圾分类</div>
<div>可回收物</div>
<div>厨余垃圾</div>
<div>其他垃圾</div>
<div>有害垃圾</div>
</div>
<div class="bottom">
<div class="show">
<h2>欢迎来到生活垃圾分类首页</h2>
<label>垃圾名称:</label>
<input type="text" name="" id="user"/>
<br>
<div class="add">
<button id="add1">添加到可回收物</button>
<button id="add2">添加到厨余垃圾</button>
<button id="add3">添加到其他垃圾</button>
<button id="add4">添加到有害垃圾</button>
</div>
</div>
</div>
js部分
var divs=document.querySelectorAll(".top>div")
var divs1=document.querySelectorAll(".bottom>div")
console.log(divs,divs1);
for( var i=0; i<divs.length; i++){
divs[i].index = i;
divs[i].onclick =function(){
for(var j=0; j<divs1.length; j++){
divs[j].className = "";
divs1[j].className ="";
}
this.className = "active";
divs1[this.index].className = "show";
}
}
jq实现
css部分
<style>
*{
margin: 0;
padding: 0;
}
.warp{
width: 100%;
}
ul li{
list-style: none;
}
.top{
width: 300px;
height: 30px;
display: flex;
}
.top li{
flex-direction: row;
width: 200px;
height: 30px;
line-height: 30px;
border: solid 1px black;
text-align: center;
}
.top .active{
background-color: paleturquoise;
color: white;
}
.buttom>div{
width: 300px;
height: 200px;
border: solid 1px black;
display: none;
}
.buttom .show{
display: block;
}
</style>
jq部分
<script>
$(".top>li").on("click",function(){
var index= $(this).index();
$(this).addClass("active").siblings().removeClass("active");
$(".buttom>div").eq(index).addClass("show").siblings().removeClass("show");
})
</script>
总而言之jq的写法相对原生js来说简化了好多! 仅供参考!