如何用JavaScript实现单按钮切换网页背景色(蓝/白切换)
实现背景色切换按钮(蓝/白)并保留其他颜色按钮功能
你可以通过在myFunction里添加判断逻辑来实现蓝/白切换,同时不影响其他按钮的功能。核心思路是每次点击时检查当前页面背景色(或用状态变量记录),如果是lightblue就切回白色,否则设置为lightblue。
方案一:用状态变量记录(推荐,兼容性更好)
这种方式不用依赖浏览器返回的颜色格式,逻辑更清晰:
JavaScript代码:
// 用变量记录当前是否处于蓝色背景状态 let isBlueBackground = false; function myFunction() { // 切换状态 isBlueBackground = !isBlueBackground; // 根据状态设置背景色 document.body.style.backgroundColor = isBlueBackground ? 'lightblue' : 'white'; } function my1Function() { document.body.style.backgroundColor= "lightgrey"; // 切换其他颜色后,重置状态变量 isBlueBackground = false; } function my2Function() { document.body.style.backgroundColor= "pink"; isBlueBackground = false; } function my3Function() { document.body.style.backgroundColor= "lightgreen"; isBlueBackground = false; }
HTML代码:
<header> <h1></h1> </header> <br> <form action="#"> <label for="fname">Uw naam:</label> <input type="text" id="fname" name="fname"> <input type="submit" value="Submit"> </form> <button type="button" onclick="myFunction()">Lightblue ↔ White</button> <button type="button" onclick="my1Function()">Lightgrey</button> <button type="button" onclick="my2Function()">Pink</button> <button type="button" onclick="my3Function()">Lightgreen</button>
方案二:通过判断当前背景色实现
如果不想额外维护状态变量,可以直接获取当前生效的背景色做判断,需要兼容不同浏览器的颜色返回格式:
function myFunction() { // 获取页面实际生效的背景色 const currentColor = window.getComputedStyle(document.body).backgroundColor; // 兼容浏览器返回的颜色名或RGB格式 if (currentColor === 'lightblue' || currentColor === 'rgb(173, 216, 230)') { document.body.style.backgroundColor = 'white'; } else { document.body.style.backgroundColor = 'lightblue'; } } // 其他函数保持不变 function my1Function() { document.body.style.backgroundColor= "lightgrey"; } function my2Function() { document.body.style.backgroundColor= "pink"; } function my3Function() { document.body.style.backgroundColor= "lightgreen"; }
关键说明
- 方案一的状态变量方式更可靠,不会因为浏览器颜色格式差异出问题,而且点击其他颜色按钮后,重置状态能保证下次点击蓝白切换按钮时逻辑正确。
- 方案二需要处理不同浏览器对颜色值的返回差异(比如Chrome会返回RGB值,Firefox可能直接返回颜色名),适合不想加额外变量的场景。
内容的提问来源于stack exchange,提问作者Jay
相关产品推荐
相关产品推荐

