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

如何编写JavaScript函数实现点击按钮时来回切换按钮颜色

实现按钮点击切换颜色的方案

以下两种常用实现方式都可以复用同一个onclick处理函数完成颜色切换需求:

方案1:直接操作行内样式(简单快速)

无需额外定义CSS,直接通过判断按钮当前背景色做状态翻转:

<!-- 按钮定义,直接绑定onclick事件,将按钮自身作为参数传入处理函数 -->
<button 
  style="background: blue; color: #fff; padding: 6px 12px; border: none; border-radius: 4px; cursor: pointer;"
  onclick="toggleBtnColor(this)"
>
  点击切换颜色
</button>

<script>
function toggleBtnColor(btn) {
  // 三元表达式判断当前颜色,切换为对应状态
  btn.style.backgroundColor = btn.style.backgroundColor === 'blue' ? 'red' : 'blue';
}
</script>

方案2:类名切换(可维护性更高,推荐)

通过切换CSS类名实现样式修改,后续调整颜色只需要修改CSS代码,无需改动JS逻辑:
首先定义样式:

.base-btn {
  color: #fff;
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.blue-state {
  background: blue;
}
.red-state {
  background: red;
}

然后是HTML和JS代码:

<button class="base-btn blue-state" onclick="toggleBtnColor(this)">点击切换颜色</button>

<script>
function toggleBtnColor(btn) {
  // classList.toggle会自动判断类名是否存在,存在则移除,不存在则添加
  btn.classList.toggle('blue-state');
  btn.classList.toggle('red-state');
}
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 17:36:07