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

如何通过原生JavaScript实现点击按钮为#infoBox添加.expanded类

原生JS实现点击元素添加类名

需求

点击#infoBox容器本身或者容器内的按钮时,给#infoBox加上.expanded类。之前找到的方案大多是jQuery写的,想换成原生JavaScript实现,下面是我写的HTML和两段没跑通的JS代码。

我的HTML结构

<div id="infoBox" class="" onclick="expand">
    <aside>
        <h4>Kontakt</h4>
        <p>Har du brug for grafisk assistance, i form af råd og vejledning, eller brug for hjælp til design af grafik? Fyr mig en besked!</p>
    </aside>
                
    <button onClick="expand" class="primaryBtn noMovement">Kontakt</button>
</div>

尝试的两段JS代码(均未成功)

// 第一段
function expand() {
    document.getElementById("infoBox") {
        classList.add("expanded");
    }
}

// 第二段
function expand() {
    document.getElementsById("infoBox").classList.add("expanded");
}

问题出在哪

  • 第一段代码语法错误:获取到元素后直接用大括号包裹方法调用是无效的,必须直接对元素对象调用classList.add()。
  • 第二段代码方法名写错:原生JS里获取单个ID元素的方法是getElementById()(单数形式),getElementsById是不存在的。
  • 额外坑:HTML里的onclick="expand"没加括号,函数不会被执行,得写成onclick="expand()"。

正确实现方式

方式1:修复原有代码

直接修正函数写法,同时改好HTML里的调用:

function expand() {
    // 获取目标元素
    const infoBox = document.getElementById("infoBox");
    // 添加.expanded类
    infoBox.classList.add("expanded");
}

HTML里的onclick="expand"要改成onclick="expand()",按钮的onClick同理。

方式2:推荐用事件监听(更规范)

内联onclick不利于代码维护,推荐用addEventListener绑定事件,代码和HTML分离:

// 获取元素
const infoBox = document.getElementById("infoBox");
const contactBtn = infoBox.querySelector(".primaryBtn");

// 定义添加类的函数
function addExpandedClass() {
    infoBox.classList.add("expanded");
}

// 给容器和按钮绑定点击事件
infoBox.addEventListener("click", addExpandedClass);
contactBtn.addEventListener("click", addExpandedClass);

这种写法不需要在HTML里写onclick属性,后续修改逻辑也更方便。

额外优化:支持切换类

如果需要点击多次能来回添加/移除.expanded类,把add换成toggle就行:

function toggleExpand() {
    document.getElementById("infoBox").classList.toggle("expanded");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:45:47