動態修改網頁背景顏色是 JavaScript 操作 DOM 樣式的經典入門範例。本文將詳細解析如何透過按鈕點擊事件,即時變更文件背景色彩,並探討現代化的最佳實踐方式。
利用 document.bgColor 屬性(或現代 document.body.style.backgroundColor)搭配按鈕的 onclick 事件,在使用者點擊時執行對應函式修改背景顏色值。
<html>
<head>
<title>Background Color Changer</title>
<script language="JavaScript">
<!--
function BG_yellow() { document.bgColor = 0xFFFF00 }
function BG_thistle() { document.bgColor = 0xD8BFD8 }
function BG_plum() { document.bgColor = 0xDDA0DD }
function BG_red() { document.bgColor = 0xFF0000 }
//-->
</script>
</head>
<body>
<center>
<form>
<font face="comic sans ms">
<br><h1> Set the background color </h1><br>
<input type="button" value="Make background Yellow" onclick="BG_yellow()"><br><br>
<input type="button" value="Make background Thistle" onclick="BG_thistle()"><br><br>
<input type="button" value="Make background Plum" onclick="BG_plum()"><br><br>
<input type="button" value="Make background Red" onclick="BG_red()">
</font>
</form>
</center>
</body>
</html>
0xRRGGBB 格式,等同於 CSS 的 #RRGGBB,如 0xFFFF00 代表黃色onclick="函式名()" 綁定點擊事件為符合當前開發規範,建議採用以下改良方案:
// HTML 結構分離
<button data-color="#FFFF00">黃色背景</button>
<button data-color="#D8BFD8">淡紫色背景</button>
// ... 其他按鈕
// JavaScript 邏輯
document.querySelectorAll('button[data-color]').forEach(btn => {
btn.addEventListener('click', () => {
document.body.style.backgroundColor = btn.dataset.color;
});
});
linear-gradient 創造豐富視覺效果localStorage 記住使用者偏好,實現深色/淺色模式持久化<input type="color"> 讓使用者自訂顏色現代瀏覽器對 document.body.style.backgroundColor 支援完善,且操作樣式物件比舊版 bgColor 更具彈性,可同時控制背景圖片、漸層、重複方式等進階屬性。