选项卡保存记录位置(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 .ac {
        background-color: pink;
      }
      #box div {
        width: 200px;
        height: 200px;
        display: none;
        border: 1px solid #ccc;
      }
    </style>
  </head>
  <body>
    <div id="box">
      <button class="ac">001</button>
      <button>002</button>
      <button>003</button>
      <div style="display: none">001</div>
      <div>002</div>
      <div>003</div>
    </div>
  </body>
  <script>
    const aBtn = document.querySelectorAll('button')
    const aDiv = document.querySelectorAll('#box div')

    const index = localStorage.index
    fn(index)

    function fn(index) {
      for (let i = 0; i < aBtn.length; i++) {
        aBtn[i].className = ''
        aDiv[i].style.display = 'none'
      }
      aBtn[index].className = 'ac'
      aDiv[index].style.display = 'block'
    }

    for (let i = 0; i < aBtn.length; i++) {
      aBtn[i].onclick = function () {
        localStorage.index = i
        fn(i)
      }
    }
  </script>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_67268153/article/details/130288199