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

如何用原生JS实现同一类名的添加与移除?鼠标移入添加,按下移除

原生JS实现按钮鼠标移入加类、按下移除类

需求:使用原生JavaScript实现,鼠标移入按钮时为按钮添加btn_sh类,鼠标按下按钮时移除该类。

以下是完整实现代码:

HTML结构

<section class="preview">
    <div class="container">
        <div class="preview__wrapper">
            <div class="preview__text">
                <h1>Navigating the digital landscape for success</h1>
                <div class="preview__descrp">Our digital marketing agency helps businesses grow and succeed online through a range of services including SEO, PPC, social media marketing, and content creation.</div>
                <button class="btn btn_prev">Book a consultation</button>
            </div>
        </div>
    </div>
</section>

SCSS样式

.btn{
    width: 231px;
    height: 68px;
    border-radius: 14px;
    border-color: #191A23;
    background-color: #fff;
    color: #000;
    font-size: 20px;
    padding: 0;
    &_prev{
        color: #fff;
        background-color: #191A23;
        width: 264px;
    }
    &_sh{
        box-shadow: 5px 5px darkgoldenrod;
    }
}

JavaScript实现(优化版)

原代码存在冗余循环和内联事件的问题,以下是更简洁易维护的实现:

// 获取目标按钮
const targetBtn = document.querySelector('.btn_prev');

// 鼠标移入:添加阴影类
targetBtn.addEventListener('mouseover', () => {
    targetBtn.classList.add('btn_sh');
});

// 鼠标按下:移除阴影类
targetBtn.addEventListener('mousedown', () => {
    targetBtn.classList.remove('btn_sh');
});

原代码问题说明

  1. 内联事件onmouseover/onmousedown不利于代码维护和事件解绑,推荐使用addEventListener
  2. 函数内部嵌套的循环完全多余,只需操作触发事件的目标元素即可
  3. classList.add/remove本身会自动处理重复添加、不存在移除的情况,无需额外判断contains

如果需要批量处理多个.btn类按钮,可以用以下写法:

const buttons = document.querySelectorAll('.btn');

buttons.forEach(btn => {
    btn.addEventListener('mouseover', () => btn.classList.add('btn_sh'));
    btn.addEventListener('mousedown', () => btn.classList.remove('btn_sh'));
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 01:04:51