一般來說,直接用 CSS 去改 Radio 單選鈕和 Checkbox 復選框的外觀是沒有效果的——這是瀏覽器作業系統原生控制項的限制。要客製化,得繞路。以下兩個方向都堪用。
思路是把真正的 input 藏起來(visibility:hidden 並壓成 0 尺寸,而非 display:none,這樣鍵盤操作還在),再讓緊鄰的 label 用一張精靈圖(sprite)呈現各種狀態,靠 background-position 切換。
form#form1 { font: 12px tahoma, sans-serif; }
input[type="checkbox"] {
visibility: hidden; width: 0; height: 0; margin: 0; padding: 0;
}
input[type="checkbox"] + label {
background: url(checkstyle.gif) no-repeat;
padding-left: 18px; color: #ccc;
}
input[type="checkbox"] + label:hover { color: #369; background-position: 0 -16px; }
input[type="checkbox"]:checked + label { color: #000; background-position: 0 -48px; }
input[type="checkbox"]:focus + label { color: #963; background-position: 0 -32px; }
input[type="radio"] {
visibility: hidden; width: 0; height: 0; margin: 0; padding: 0;
}
input[type="radio"] + label {
background: url(checkstyle.gif) no-repeat 0 -64px;
padding-left: 18px; color: #ccc;
}
input[type="radio"] + label:hover { color: #369; background-position: 0 -80px; }
input[type="radio"]:checked + label { color: #000; background-position: 0 -112px; }
input[type="radio"]:focus + label { color: #963; background-position: 0 -96px; }
關鍵是 +(相鄰兄弟選擇器)與 :checked、:focus 的組合。精靈圖每 16px 一格,分別排著未選、hover、聚焦、選中等狀態。這個做法的優點是零 JavaScript,缺點是視覺被圖片綁死,無法純靠 CSS 縮放。
另一條路是用 mootools 這類函式庫寫一個 FancyForm 物件,在運作時替容器加上 checked/unchecked、selected/unselected 等狀態 class,同時把真正的 input 移到畫面外(position:absolute; left:-9999px)但仍保留焦點能力。
HTML 結構大致如下:
<form action="" onsubmit="void(0)">
<h3>Checkboxes</h3>
<div>
<label><input type="checkbox" checked="checked"> 一個客製化樣式的核取方塊</label>
<div class="leftcol">
<label><input type="checkbox"> 選項</label>
<label><input type="checkbox" checked="checked"> 選項</label>
</div>
</div>
<h3>Radio buttons</h3>
<div class="leftcol">
<label><input type="radio" name="leftcol"> 單選</label>
<label><input type="radio" checked="checked" name="leftcol"> 單選</label>
</div>
<input type="reset" value="Reset Form">
</form>
初始化只要一行:
window.addEvent('domready', function(){ FancyForm.start(); });
這個腳本還處理了幾個細節:點擊容器時同步觸發 input 的原生事件、focus 時加上虛線外框、表單 reset 後重新同步狀態,以及同 group 的 radio 互斥更新。缺點是引入了一整個函式庫,且在今日顯得過時。
如果只需要基本樣式,純 CSS 加精靈圖已經足夠,而且效能與可及性都更好。若想保留原生控制項的語意又要有自訂外觀,可以考慮用 appearance: none 搭配 :checked 與偽元素,這是目前的標準做法,不需要藏 input 也不需要 JavaScript。