使用classList和dataset实现tab切换

显示效果:

使用classList和dataset实现tab切换

代码实现:

<!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>tab切换</title>
  <style>
    .tab {
      width: 400px;
      margin: 200px auto;
    }
    .nav {
      width: 100%;
      height: 50px;
    }
    .nav a {
      width: 25%;
      height: 100%;
      float: left;
      line-height: 50px;
      background: gray;
      color: red;
      text-align: center;
      text-decoration: none;
    }
    .nav a.now {
      background: yellow;
      color: red;
    }
    .content {
      width: 100%;
      height: 350px;
      overflow: hidden;
    }
    .content section {
      width: 100%;
      height: 100%;
      display: none;
    }
    .content section.active {
      display: block;
    }
  </style>
</head>
<body>
  <div class="tab">
    <!-- 导航栏 -->
    <nav class="nav">
      <a href="javascript:;" data-content="one">新闻1</a>
      <a href="javascript:;" data-content="two">新闻2</a>
      <a href="javascript:;" data-content="three">新闻3</a>
      <a href="javascript:;" data-content="four">新闻4</a>
    </nav>
    <!-- 内容栏 -->
    <div class="content">
      <section id="one">
          新闻1
      </section>
      <section id="two">
          新闻2
      </section>
      <section id="three">
          新闻3
      </section>
      <section id="four">
          新闻4
      </section>
    </div>
  </div>
  <script>
    (function(index){
      /* 初始化默认选中第一个选项卡 */
      /* 得到a标签组成的伪数组 */
      var nav = document.querySelector('.nav');
      var aList = nav.querySelectorAll('a');
      /* 根据索引初始化默认显示的页签和内容 */ 
      var initA = aList[index];
      // console.log(initA);
      /* 给索引为0的a标签添加now类名 */
      initA.classList.add('now');
      /* 获取自定义类名的值,即为内容的ID */
      var initId = initA.dataset.content;
      // console.log(initId);
      /* 拼接id,选取对应的内容区域 */
      var initCon = document.querySelector('#' + initId);
      /* 增加active类名——初始化完成 */
      initCon.classList.add('active');
      /* 事件委托:点击事件选中相应的选项卡,然后获取这个元素,先删除原来有
      类名now的选项卡,和对应内容的active,然后给这个元素添加类
      名now,和对应id的内容选项增加类名active */
      nav.onclick = function(e) {
        /* 获取点击的a标签 */
        var currentA = e.target;
        /* 获取原来的a标签 */
        var oldA = document.querySelector('.now');
        var oldC = document.querySelector('.active');
        /* 移除原来初始化的类名 */
        oldA.classList.remove('now');
        oldC.classList.remove('active');
        /* 给当前点击的a标签添加now类名 */
        currentA.classList.add('now');
        /* 获取点击的a标签的自定义类名的值,即为内容的ID */
        var nowId = currentA.dataset.content;
        /* 拼接id,选取对应的内容区域 */
        var nowCon = document.querySelector('#' + nowId);
        /* 增加active类名——点击事件完成 */
        nowCon.classList.add('active')
      }
    })(0)
  </script>
</body>
</html>