JS 简易tab切换

html部分

<div class="container">

     <a href="#" class="item active" data-id="1">按钮1</a><a href="#" class="item" data-id="2">按钮2</a>

     <div class="box active box1">盒子1</div>  

    <div class="box box2">盒子2</div>

</div>

 

 css部分

*{

margin: 0;

padding: 0;

}

a{

text-decoration: none;

}

.container{

width: 400px;

border: 1px solid #ff6700;

margin: 100px auto;

}

.item{

display: inline-block;

width: 200px;

height: 40px;

line-height: 40px;

background-color: lightblue;

text-align: center;

color: yellow;

}

.item.active{

background-color: lightgreen;

}

.box{

width: 400px;

height: 200px;

background-color: orange;

display: none;

}

.box:first-of-type{

background-color: lightcoral;

}

.box.active{

display: block;

}

 

 

 

js部分

let tabs = document.querySelectorAll(".item");

//遍历所有的tabs

tabs.forEach(function(item){

//给每一个item绑定事件

item.addEventListener("click",function(e){

// e.preventDefault();

// 如果点击的item已经具有active类名不需要做任何操作

if(!item.classList.contains("active")){

// 将具有active类名的item的active类名去掉

document.querySelector(".item.active").classList.remove("active");

// 给item添加上active类名

item.classList.add("active");

 

// 让当前显示的box隐藏

document.querySelector(".box.active").classList.remove("active");

// 让对应的新的box显示

let dataId = item.dataset.id;

document.querySelector(".box"+dataId).classList.add("active");

}

});

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值