原生單選按鈕樣式單調,透過 CSS 可以將它替換成更漂亮的圖標樣式。做法是隱藏原生 radio,再用 label 搭配背景圖呈現自訂外觀,並用 :checked 選擇器切換選中狀態的圖片。
<!DOCTYPE html >
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>更換單選按鈕顯示樣式</title>
<style>
input[type='radio'].radio {opacity:0; display:inline-block; height:20px; }
label.radio {background:url(imgs/radio_check.png) no-repeat; height:20px; padding-left:25px;}
input[type='radio'].radio:checked + .radio {background:url(imgs/radio_checked.png) no-repeat;}
</style>
</head>
<body>
<input type="radio" name="gender" id="x" value="X"><label for="x">我要保密</label><br>
<input type="radio" name="gender" id="y" value="M"><label for="y">我是帥哥</label><br>
<input type="radio" name="gender" id="z" value="F"><label for="z">我是美女</label><br>
<input type="radio" name="sex" id="a" value="X" class="radio"><label for="a" class="radio">我要保密</label><br>
<input type="radio" name="sex" id="b" value="M" class="radio"><label for="b" class="radio" >我是帥哥</label><br>
<input type="radio" name="sex" id="c" value="F" class="radio"><label for="c" class="radio" >我是美女</label><br>
</body>
</html>
上面兩組對比:第一組是原生單選按鈕,第二組則套用了我們自訂的圖標樣式。核心技巧是透過 input:checked + .radio 這個相鄰兄弟選擇器,在選中時切換 label 的背景圖。