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

如何用Vanilla JS实现按钮间active类的切换?

多按钮互斥切换Active类(Vanilla JS实现)

核心思路

点击任意按钮时,先移除所有按钮的active类,再为当前点击的按钮添加active类,确保同一时间只有一个按钮处于激活状态(绿色背景)。

完整代码示例

CSS 代码

.active {
    background-color: green;
}

HTML 代码(整合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>Button Active Toggle</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <button>Button1</button>
    <button class="active">Button2</button>
    <button>Button3</button>

    <script>
        // 获取页面中所有按钮元素
        const buttons = document.querySelectorAll('button');

        // 为每个按钮绑定点击事件
        buttons.forEach(button => {
            button.addEventListener('click', function() {
                // 移除所有按钮的active类
                buttons.forEach(btn => btn.classList.remove('active'));
                // 给当前点击的按钮添加active类
                this.classList.add('active');
            });
        });
    </script>
</body>
</html>

代码细节说明

  • document.querySelectorAll('button'):获取页面中所有<button>元素,返回一个节点列表。
  • forEach遍历按钮:给每个按钮绑定点击事件监听。
  • 点击事件逻辑:
    1. 再次遍历所有按钮,调用classList.remove('active')移除激活类。
    2. 通过this获取当前点击的按钮,调用classList.add('active')添加激活类。

优化思路(可选)

如果页面中只有这些按钮使用active类,可以用更高效的方式找到当前激活的按钮,避免遍历所有按钮:

button.addEventListener('click', function() {
    // 找到当前激活的按钮
    const currentActiveBtn = document.querySelector('.active');
    // 若存在则移除其active类
    if (currentActiveBtn) currentActiveBtn.classList.remove('active');
    // 给当前按钮添加active类
    this.classList.add('active');
});

内容的提问来源于stack exchange,提问作者Mohiul Islam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 05:10:54