You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaScript EventListener切换HTML Section Active类失效问题

问题:点击按钮无法切换Section的Active类

我有一个包含5个按钮和5个section的HTML页面,原本期望点击任一按钮时,通过JavaScript切换对应section的active类,但目前点击按钮后,section的active状态没有变化。

原代码

HTML部分

<!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>Portfolio</title>
  <link rel="stylesheet" href="styles/styles.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer"
  />
</head>

<body class="main-content">
  <header class="section sec1 header active" id="home">

  </header>
  <main>
    <section class="section sec2 about" id="about"></section>
    <section class="section sec3 portfolio" id="portfolio"></section>
    <section class="section sec4 blogs" id="blogs"></section>
    <section class="section sec5 contact" id="contact"></section>
  </main>
  <div class="controls">
    <div class="control control-1 active-btn" data-id="home">
      <i class="fa-solid fa-house"></i>
    </div>
    <div class="control control-2 " data-id="about">
      <i class="fa-solid fa-user"></i>
    </div>
    <div class="control control-3 " data-id="portfolio">
      <i class="fa-solid fa-briefcase"></i>
    </div>
    <div class="control control-4 " data-id="blogs">
      <i class="fa-solid fa-newspaper"></i>
    </div>
    <div class="control control-5 " data-id="contact">
      <i class="fa-solid fa-envelope-open"></i>
    </div>
  </div>

  <script src="app.js"></script>
</body>

</html>

JavaScript部分

const sections = document.querySelectorAll('.section');
const sectBtns = document.querySelectorAll('.controls');
const sectBtn = document.querySelectorAll('.control');
const allSections = document.querySelectorAll('.main-content');

function pageTransition() {
  //Button click active class
  for (let i = 0; i < sectBtn.length; i++) {
    sectBtn[i].addEventListener('click', function() {
      let currentBtn = document.querySelectorAll('.active-btn');
      currentBtn[0].className = currentBtn[0].className.replace('active-btn', '');
      this.className += 'active-btn';
    })
  }

  //sections Active class
  allSections.addEventListener('click', (e) => {
    const id = e.target.dataset.id;
    if (id) {
      //remove selected from the other btns
      sectBtns.forEach((btn) => {
        btn.classList.remove('active')
      })
      e.target.classList.add('active')

      //hide other sections
      sections.forEach((section) => {
        section.classList.remove('active')
      })

      const element = document.getElementById(id);
      element.classList.add('active');
    }
  })
}

pageTransition()

问题分析

  1. 事件绑定错误:allSections是document.querySelectorAll('.main-content')返回的NodeList,无法直接调用addEventListener,且绑定到body元素上的逻辑不合理,导致点击按钮时section切换逻辑无法正确触发。
  2. 类名操作错误:用this.className += 'active-btn'拼接类名时缺少空格,会生成control control-1active-btn这类无效类名,导致样式失效。
  3. 逻辑拆分冗余:按钮激活和section切换的逻辑分开处理,容易导致状态不同步。

修复后的代码

const sections = document.querySelectorAll('.section');
const sectBtns = document.querySelectorAll('.control');

function pageTransition() {
  sectBtns.forEach(btn => {
    btn.addEventListener('click', function() {
      // 重置所有按钮的激活状态
      sectBtns.forEach(b => b.classList.remove('active-btn'));
      // 激活当前点击的按钮
      this.classList.add('active-btn');

      // 获取对应section的ID
      const targetId = this.dataset.id;
      if (targetId) {
        // 重置所有section的激活状态
        sections.forEach(section => section.classList.remove('active'));
        // 激活目标section
        document.getElementById(targetId).classList.add('active');
      }
    });
  });
}

pageTransition();

修复说明

  • 直接给每个按钮绑定点击事件,逻辑集中更易维护。
  • 使用classList.add()/classList.remove()操作类名,避免字符串拼接错误。
  • 按钮激活和section切换逻辑合并,确保状态同步。

内容的提问来源于stack exchange,提问作者Francois-xavier Savoie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 15:26:09