如何在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
相关产品推荐
相关产品推荐

