十一行js代码实现选项卡(标签页)

 

效果图如上, 下面直接放代码

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
      .box {
        width: 450px;
        height: 350px;
        margin: 50px auto;
      }

      .ul1,
      .ul2 {
        width: 450px;
        list-style: none;
        margin: 0;
        padding: 0;
      }

      li {
        margin: 0;
        padding: 0;
        text-align: center;
        font-size: 30px;
      }

      .ul1 {
        display: flex;
      }

      .ul1 li {
        width: 150px;
        height: 50px;
        background-color: grey;
        line-height: 50px;
      }

      .ul1 li.active {
        background-color: red;
      }

      .ul2 {
        position: relative;
        height: 300px;
      }

      .ul2 li {
        width: 450px;
        height: 300px;
        background-color: purple;
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
        line-height: 300px;
      }

      .ul2 li.active {
        opacity: 1;
      }
    </style>
  </head>

  <body>
    <div class="box">
      <ul class="ul1">
        <li class="active">1</li>
        <li>2</li>
        <li>3</li>
      </ul>
      <ul class="ul2">
        <li class="active">one</li>
        <li>two</li>
        <li>three</li>
      </ul>
    </div>
  </body>

</html>
<script>
  // 首先获取按钮和标签页
  var btns = document.querySelectorAll('.ul1>li')
  var views = document.querySelectorAll('.ul2>li')
  // 假设一个索引值来表示当前被选中的卡片和按钮
  var index = 0
  // 先遍历按钮,得到所有按钮
  btns.forEach((ele, i) => {
    // 给没个按钮添加事件监听
    ele.onclick = function () {
      // 首先清除按钮和卡片的被选中样式
      btns[index].className = ''
      views[index].className = ''
      // 将当前被选中的按钮和卡片索引值赋值给假设的索引值
      index = i
      // 再给被选中的索引值添加选中样式的类名
      btns[index].className = 'active'
      views[index].className = 'active'
    }
  });
</script>

希望各位大佬发现bug后能提醒本人一下,总感觉这么点代码可能会有遗漏。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值