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

如何用JavaScript DOM实现按钮切换页面背景色?

实现背景色切换功能:点击切换salmon色/恢复原色

你的现有代码只能将背景色设置为salmon,无法实现再次点击恢复原色的效果,核心问题是缺少对当前背景状态的判断。下面提供两种简洁的实现方案:

方案一:通过颜色值判断切换

先保存页面初始背景色,点击按钮时对比当前背景色,决定切换方向:

const cColor = document.getElementById("cColor");
// 兼容行内样式与默认样式,获取初始背景色
const originalBg = document.body.style.backgroundColor || window.getComputedStyle(document.body).backgroundColor;

cColor.onclick = function() {
  const currentBg = document.body.style.backgroundColor || window.getComputedStyle(document.body).backgroundColor;
  // 浏览器可能将颜色转为rgb格式,需同时判断两种值
  if (currentBg === "salmon" || currentBg === "rgb(250, 128, 114)") {
    document.body.style.backgroundColor = originalBg;
  } else {
    document.body.style.backgroundColor = "salmon";
  }
};

方案二:使用CSS类切换(推荐)

将样式逻辑剥离到CSS中,通过classList.toggle()自动添加/移除类,代码更简洁易维护:

CSS 代码

body {
  text-align: center;
}

.bg-salmon {
  background-color: salmon;
}

JavaScript 代码

const cColor = document.getElementById("cColor");
cColor.onclick = function() {
  // toggle方法自动检测类的存在状态,存在则移除,不存在则添加
  document.body.classList.toggle("bg-salmon");
};

完整可运行示例

<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    body {
      text-align: center;
    }
    .bg-salmon {
      background-color: salmon;
    }
  </style>
</head>
<body>
  <h1>Change Background Color</h1>
  <button type="button" id="cColor">Toggle Color</button>
  <script>
    const cColor = document.getElementById("cColor");
    cColor.onclick = function() {
      document.body.classList.toggle("bg-salmon");
    };
  </script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:39:18