JavaScript的排他思想

196 阅读1分钟

一、含义

  • 排除所有元素(包括自己),接着再设置自己或者对应的元素
  • 使用方式
    1.干掉所有人 使用for循环 2.复活他自己 通过this或者下标找到自己或者对应的元素
    举个栗子
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Document</title>
  <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: green;
    }
  </style>
</head>

<body>
  <ul class="list">
    <li class="active">首页</li>
    <li>文章列表</li>
    <li>发表文章</li>
    <li>关于我们</li>
  </ul>
  <script>
    // 方法一 干掉所有元素 再给当前元素添加样式
    // // 获取元素
    // let lis = document.querySelectorAll('li')
    // // 遍历伪数组lis 为每个li绑定单击事件
    // for (let i = 0; i < lis.length; i++) {
    //   lis[i].addEventListener('click', function () {
    //     console.log('123');
    //     // 干掉所有元素的active样式
    //     lis.forEach(function (ele, i) {
    //       ele.classList.remove('active')
    //     })
    //     // 为当前的li元素添加active样式
    //     this.classList.add('active')
    //   })
    // }

    // 方法二 干掉有该样式的元素 再给当前元素添加样式
    // 获取元素
    let lis = document.querySelectorAll('li')
    // 遍历数组
    for (let i = 0; i < lis.length; i++) {
      // 为li绑定单击事件
      lis[i].addEventListener('click', function () {
        console.log('123');
        // 找到li元素下有active样式的元素干掉他   交集选择器 li.active满足他是li的同时还包含active样式
        document.querySelector('li.active').classList.remove('active')
        // 给当前元素添加active样式
        this.classList.add('active')
      })
    }
  </script>
</body>

</html>