本文分享一個小yet實用的特效:用 radio 單選框做網頁背景顏色選擇器。點擊對應顏色的單選框,頁面背景就立刻變成該色,代碼量極小,很適合拿來做主題皮膚切換的入門練習。
運行效果如下圖所示:

在線演示地址:
https://demo.jb51.net/js/2015/js-radio-cha-bgcolor-codes/
完整代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>radio顏色選擇器</title> <body> <FORM METHOD="POST" NAME="bgcolor"> <font color="silver">click here</font><input type="radio" name="bgcolor" ONCLICK="document.bgColor='silver'"><BR> <font color="lightslategray">click here</font><input type="radio" name="bgcolor" ONCLICK="document.bgColor='lightslategray'"><BR> <font color="azure">click here</font><input type="radio" name="bgcolor" ONCLICK="document.bgColor='azure'"><BR> <font color="lightgreen">click here</font><input type="radio" name="bgcolor" ONCLICK="document.bgColor='lightgreen'"><
等等,仔細看會發現上面第四行有個筆誤,正確的代碼應為:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>radio顏色選擇器</title> </head> <body> <FORM METHOD="POST" NAME="bgcolor"> <font color="silver">click here</font><input type="radio" name="bgcolor" ONCLICK="document.bgColor='silver'"><BR> <font color="lightslategray">click here</font><input type="radio" name="bgcolor" ONCLICK="document.bgColor='lightslategray'"><BR> <font color="azure">click here</font><input type="radio" name="bgcolor" ONCLICK="document.bgColor='azure'"><BR> <font color="lightgreen">click here</font><input type="radio" name="bgcolor" ONCLICK="document.bgColor='lightgreen'"><BR> <font color="lightblue">click here</font><input type="radio" name="bgcolor" ONCLICK="document.bgColor='lightblue'"><
核心只有一句:
document.bgColor = '顏色值'。所有 radio 共用同一個 name,因此天然互斥,點哪個哪個選中。現代寫法建議
這份代碼保留了濃厚的年代感,若重新實現,建議這樣調整:
用
document.body.style.backgroundColor取代 document.bgColor。後者是 DOM Level 0 遺留的屬性,雖然目前浏覽器仍支持,但已不屬於標準寫法。用
<font>標籤描述顏色早已被廢棄,應改為 CSS;<BR>換行也應由容器的 display 控制。把 ONCLICK 內聯事件改為 addEventListene 綁定,並用 data-color 屬性存顏色值,遍歷綁定,這樣新增一個色塊只需複製一行 HTML,不必改 JS。
如果想做成真正的皮膚切換,更合適的做法是准備多套 CSS 文件或 CSS 變量,切換時替換 class 或改寫 root 上的自定義屬性,而不是逐個元素改樣式。
以上就是 radio 背景顏色選擇器的完整實現與改進思路,希望對大家的 JavaScript 開發有所幫助。