js + 原生HTML——实现tab切换

实现动态切换效果,且按钮位置可变,不固定,可切换至任意位置 

 

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
 
</head>
<style type="text/css">
  .mod-tab .tab{
  float:left;
  padding:5px 20px;
  border-top:1px solid #ccc;
  border-left:1px solid #ccc;
  background-color:#ddd;
}
.header .tab:last-child{
  border-right:1px solid #ccc;
}
.content{
  border:1px solid #ccc;
  width:300px;
  height:200px;
}
.header::after{
  content:'';
  display:block;
  clear:both;
}

.mod-tab .header .active{
  background-color:#fff;
}

.mod-tab .content .panel{
  display:none
}
.mod-tab .content .active{
  display:block;
}
/*.button1{
  position: fixed;
  left:500px;
  top: 100px
}*/
.tab{
  display: block;
}
</style>
<body>
  <div class="mod-tab">
    <div class="header">
      
        <button class="tab active button1">1</button>
        <button class="tab button2">2</button>
        <button class="tab button3">3</button>
        <button class="tab button4">4</button>
    </div>
    <div class="content">
      <div class="panel active">
        <div>panel1</div>
        <div>anel1</div>
        <div>nel1</div>
      </div>
      <div class="panel">panel2</div>
      <div class="panel">panel3</div>
      <div class="panel">panel4</div>
    </div>
  </div>
</body>
<script type="text/javascript">
  document.querySelectorAll('.tab').forEach(function(node){
  node.addEventListener('click',function(){
    var index
    this.parentElement.querySelectorAll('.tab').forEach(function(e,inx){
      //e.style.display='none' 跳转的时候隐藏按钮
      e.classList.remove('active')
      if(node === e){
        index=inx
      }
    })
    this.classList.add('active')
    this.parentElement.nextElementSibling.querySelectorAll('.panel').forEach(function(panel){
      panel.classList.remove('active')
    })
   this.parentElement.nextElementSibling.querySelectorAll('.panel')[index].classList.add('active')
  })
})
</script>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值