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

如何在HTML中创建点击后更改网页背景为红、绿、蓝的三个按钮?

实现点击按钮切换网页背景色

现有代码的问题

  • 仅修改了H1元素的文字颜色,而非网页背景色
  • 缺少Green、Blue两个按钮及对应功能逻辑

修正后的完整代码

<h1 id="H1">H1</h1>
<button type="button" onclick="changeBackgroundColor('red')">Red</button>
<button type="button" onclick="changeBackgroundColor('green')">Green</button>
<button type="button" onclick="changeBackgroundColor('blue')">Blue</button>

<script>
function changeBackgroundColor(color) {
  // 设置body的背景色,覆盖整个网页区域
  document.body.style.backgroundColor = color;
}
</script>

代码说明

  • 三个按钮共用同一个函数changeBackgroundColor,通过传入不同的颜色值(支持颜色名称、十六进制、RGB等格式)实现对应效果
  • 使用document.body.style.backgroundColor修改网页背景,因为body元素默认覆盖整个视口范围,能实现全屏背景切换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 21:15:33