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

如何用JS实现点击同一按钮切换CSS div的背景样式

点击同一按钮切换div背景样式的实现方法

你可以通过if-else判断当前div的背景色状态,切换对应的颜色值即可,修改后的代码如下:

JS代码

function changeBg() {
  var divElem = document.getElementById("change-bg");
  // 调用getComputedStyle获取实际渲染的背景色,兼容性更好
  var currentBg = window.getComputedStyle(divElem).backgroundColor;
  // 黄色对应的rgb值为rgb(255,255,0),直接比对rgb值避免不同浏览器颜色返回格式差异问题
  if(currentBg === "rgb(255, 255, 0)") {
    divElem.style.backgroundColor = "red";
  } else {
    divElem.style.backgroundColor = "yellow";
  }
}

CSS代码(和原代码一致无需修改)

body {
  margin: 0;
}

#change-bg {
  /* Extra Text Formatting */
  padding: 10px;
  text-align: center;
  /* Primary Background Color */
  background-color: yellow;
}

HTML代码(和原代码一致无需修改)

<div id="change-bg">
  <h3>
    Hello World
    <br/>
    <button onclick="changeBg();">Change Color</button>
  </h3>
</div>

更易维护的优化方案

如果后续需要切换的样式规则更多,推荐使用类名切换的方案实现,代码更简洁也更容易扩展:

  1. 首先在CSS中新增激活态类:
#change-bg.active {
  background-color: red;
}
  1. JS代码直接调用toggle方法切换类即可:
function changeBg() {
  var divElem = document.getElementById("change-bg");
  divElem.classList.toggle("active");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:57:03