原生js实现tab栏选项卡

这篇博客展示了如何使用JavaScript实现菜单项与对应内容的交互。当点击顶部菜单的某个选项时,底部相应的内容区域会显示,同时选中项会高亮显示,其他菜单项恢复默认样式。此功能通过设置元素的class和display属性实现。
  var top1 = document.getElementById('top').getElementsByTagName('li')
  var bot1 = document.getElementById('bottom').getElementsByTagName('div')
  console.log(bot1);
  for(var i= 0;i<top1.length;i++){
    top1[i].setAttribute('index',i)
    top1[i].onclick = function(){
      for(var i= 0;i<top1.length;i++){
        top1[i].className = ''
      }
      this.className = 'current'      //点击哪一个给哪个加类名,变色
     var index = this.getAttribute('index')  //给上面的几栏设置属性
     for(var i= 0;i<top1.length;i++){
      bot1[i].style.display = 'none'   
     }
     bot1[index].style.display = 'block'
    }
  }
  .yifu{
    width: 300px;
    height: 300px;
    background-color: darkkhaki;
  }
  .fruit{
    width: 500px;
    height: 500px;
    background-color: cyan;
  }
  .phone{
    width: 600px;
    height: 300px;
    background-color: blue;
  }
  .block{
    display: block
  }
  .item{
    display: none;
  }
  .max_con{
    width: 500px;
    height: 500px;
    margin: 0 auto;
  }
  li{
  list-style: none;
  }
  #top{
    width: 400px;
    height: 50px;
    /* background-color: red; */
  }
  .bottom>div{
    /* float: left; */
    width: 50px;
    height: 50px;
    text-align: center;
    line-height: 50px;
  }
  #bottom{
    width: 400px;
    height: 50px;
    /* background-color: blue; */
  }
  #top>li{
    float: left;
    width: 50px;
    height: 50px;
    text-align: center;
    line-height: 50px;
    /* background-color: cyan; */
  }
  .current{
    background-color: yellow;
  }
    <div class="max_con">
        <div id="top">
          <li class="current">手机</li>
          <li>水果</li>
          <li>服装</li>
        </div>
        <div id="bottom">
        <div class="item phone" style="display: block;">手机</div>
        <div class="item fruit">水果</div>
        <div class="item yifu">服装</div>
        </div>
      </div>
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值