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

如何实现按钮文本在鼠标悬浮/点击时的对应颜色切换

问题分析与解决方案

你的代码存在几个关键问题导致无法正常运行,以下是修正后的实现方案:

代码错误点

  • document.getElementsByClassName返回的是HTMLCollection类数组对象,不能直接调用addEventListener,需要获取单个元素(比如[0])或者遍历处理。
  • 方法名拼写错误:document.getElementsById应为document.getElementById(id是唯一的,所以方法名是单数形式)。

修正后的JavaScript实现

// 获取单个按钮元素(如果有多个按钮需要遍历处理)
const offerBTN = document.getElementsByClassName("button")[0];
const title = document.getElementById("button_title");
const subtitle = document.getElementById("subtitle");

offerBTN.addEventListener('mouseenter', function () {
    title.style.color = "rgb(170, 170, 170)";
    subtitle.style.color = "rgb(170, 170, 170)";
})

offerBTN.addEventListener('mouseup', function () {
    title.style.color = "rgb(170, 170, 170)";
    subtitle.style.color = "rgb(0, 0, 0)";
})

offerBTN.addEventListener('mouseleave', function () {
    title.style.color = "rgb(200, 100, 100)"; // 未选中状态
    subtitle.style.color = "rgb(100, 200, 100)";
})

offerBTN.addEventListener('mousedown', function () {
    title.style.color = "rgb(100, 200, 100)";
    subtitle.style.color = "rgb(100, 100, 200)"; // 选中状态
})

更简洁的CSS实现(推荐)

其实不需要JavaScript,用CSS伪类就能实现相同效果,代码更简洁易维护:

<style>
/* 默认状态 */
.button #button_title {
    color: rgb(200, 100, 100);
}
.button #subtitle {
    color: rgb(100, 200, 100);
}

/* 鼠标进入按钮 */
.button:hover #button_title,
.button:hover #subtitle {
    color: rgb(170, 170, 170);
}

/* 鼠标按下按钮 */
.button:active #button_title {
    color: rgb(100, 200, 100);
}
.button:active #subtitle {
    color: rgb(100, 100, 200);
}

/* 鼠标松开按钮(模拟mouseup效果) */
.button:focus:not(:active) #button_title {
    color: rgb(170, 170, 170);
}
.button:focus:not(:active) #subtitle {
    color: rgb(0, 0, 0);
}
</style>

<button class="button">
    <h3 id="button_title">Job Position 10 ></h3>
    <p id="subtitle">City, Country | Department | Keyword</p>
</button>

CSS方案说明

  • :hover对应鼠标进入元素的状态
  • :active对应鼠标按下元素的状态
  • :focus:not(:active)对应鼠标松开后按钮保持聚焦的状态,匹配mouseup的需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:15:44