問題:javascript
默認的radio控件不是很好看,咱們可否自定義一個radio圖標?css
解決:html
1.radio有input和lable兩個標籤。java
2.<input>是前面的圖標,選中後圖標變化。ios
3.<label> 標籤爲 input 元素定義標註(標記)。label 元素不會向用戶呈現任何特殊效果。不過,它爲鼠標用戶改進了可用性。若是您在 label 元素內點擊文本,就會觸發此控件。就是說,當用戶選擇該標籤時,瀏覽器就會自動將焦點轉到和標籤相關的表單控件上。web
4.咱們有三種思路達到效果:瀏覽器
4.1修改<input>中圖標的樣式。該方法關鍵點在因而否有這些 css熟悉。服務器
4.2經過事件機制:某個radio控件被選中後,經過添加js事件動態改變某些radio控件的背景圖片。ui
4.3隱藏<input>圖標,在<label>中存放你自定義的背景圖片和文字,直接使用css的background屬性來顯示自定義圖標。url
5.這裏看看4.3的實現代碼:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <style type="text/css"> /*兩個複選框box浮動,方便設置css*/ .radio{ display:-moz-box; display:-webkit-box; display:box; float:left; } /*讓原有的複選框圖案隱藏*/ .radios input[type=radio]{ display: none; } /*圖片和文字都放在label裏面*/ .radios label{ display:-moz-box; display:-webkit-box; display:box; float:left; line-height: 20px;/*不設行高文字垂直方向不居中*/ text-indent: 30px;/*使文字縮進:文字和圖片都在label裏面,不縮進文字和圖片疊加在一塊兒*/ background:url(no.png) no-repeat left top;/*背景圖片*/ background-size: 20px 20px;/*設置背景圖片大小*/ } .radios input[type=radio]:checked + .radio{ background:url(yes.png) no-repeat left top;/*被選中時,換背景圖片*/ background-size: 20px 20px; } </style> </head> <body> <div id="box" style="margin:100px 0 0 100px;"> <p style="font-size:16px; color:#000000; float:left; margin:0 20px 30px 0">審覈結果<p> <div class="radios"> <input type="radio" name="rGroup" id="r1" checked="checked" /> <label class="radio" for="r1" style="font-size:14px; color:#333333;">經過</label> <input type="radio" name="rGroup" id="r2" /> <!--name:表單(form)的控件名,提交的數據都用name來控制。如checkbox和radio,有多個name會同時對應多個控件來標識其屬於一個radio。此外瀏覽器會根據name來設定發送到服務器的request--> <label class="radio" for="r2" style="font-size:14px; color:#333333; margin-left:70px">否決</label> </div> </div> </body> <!--script必須放在body下面,不然getElementById找不到id--> <script type="text/javascript"> var tmp = document.getElementById("r1"); tmp.addEventListener("change",radioclick,false); var tmp2 = document.getElementById("r2"); tmp2.addEventListener("change",radioclick2,false); function radioclick(){ alert("審覈結果:經過!!"); } function radioclick2(){ alert("審覈結果:否決!!"); } </script> </html>
上面的背景圖片no.png 和yes.png是你自定義的圖片;
效果以下:
選中「經過」,跳出「審覈結果:經過!!」提示:
「經過」和「否決」前面的圖標,都是能夠自定義的,並且選中以後圖標會跟着變,達到預期效果!
選中「否決」,跳出「審覈結果:否決!!」提示: