JS排他思想

优化前:

 <style>
      ul {
        list-style: none;
        width: 600px;
        display: flex;
        height: 50px;
      }
      li {
        flex: 1;
        background-color: #ccc;
        border-right: 1px solid blue;
        line-height: 50px;
        text-align: center;
      }
      .active {
        background-color: orange;
      }
    </style>
  </head>
  <body>
    <ul class="list">
      <li>首页</li>
      <li>文章列表</li>
      <li class="active">发表文章</li>
      <li>关于我们</li>
    </ul>

    <script>
      // 1.获取元素
      let lis = document.querySelectorAll('li')
      // 2.遍历伪数组,为其中的每个元素绑定单击事件
      for (let i = 0; i < lis.length; i++) {
        lis[i].addEventListener('click', function() {


          // 3.1 干掉所有元素的active样式
          lis.forEach(function(ele, index) {
            ele.classList.remove('active')
          })

          // 3.2 为当前元素添加active样式
          // lis[i].classList.add('active')
          this.classList.add('active')


          
        })
      }
    </script>

优化后:移除遍历 找到当前有active样式的li元素,清除它的active样式

<style>
    ul {
      list-style: none;
      width: 600px;
      display: flex;
      height: 50px;
    }

    li {
      flex: 1;
      background-color: #ccc;
      border-right: 1px solid blue;
      line-height: 50px;
      text-align: center;
    }

    .active {
      background-color: orange;
    }
  </style>
</head>

<body>
  <ul class="list">
    <li>首页</li>
    <li>文章列表</li>
    <li class="active">发表文章</li>
    <li>关于我们</li>
  </ul>

  <script>
    // 1.获取元素
    let lis = document.querySelectorAll('li')
    // 2.遍历伪数组,为其中的每个元素绑定单击事件
    for (let i = 0; i < lis.length; i++) {
      lis[i].addEventListener('click', function () {


        // // 3.1 干掉所有元素的active样式
        // lis.forEach(function(ele, index) {
        //   ele.classList.remove('active')
        // })
        // 3.1 找到当前有active样式的li元素,清除它的active样式
        // li.active:交集选择器:要求它是li元素的同时还要拥有active样式
        document.querySelector('li.active').classList.remove('active')

        // 3.2 为当前元素添加active样式
        // lis[i].classList.add('active')
        this.classList.add('active')

      })
    }
  </script>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值