如今前端頁面效果日益豐富,默認的input組件樣式顯然已經不能知足需求。趁着此次開發的頁面中有這方面的需求,在這裏整理一下修改
radio
、checkbox
、select
的方法。javascript
修改radio的默認樣式有兩種經常使用的方法css
此方法需藉助CSS3,關鍵CSS代碼以下前端
.demo1 input[type='radio'],.demo1 input[type="checkbox"]{ display:none; } .demo1 label:before{ content: ""; display: inline-block; width: 17px; height: 16px; margin-right: 10px; position: absolute; left: 0; bottom: 0; background-color: #3797fc; } .demo1 input[type='radio'] + label:before{ border-radius: 8px; } .demo1 input[type='checkbox'] + label:before{ border-radius: 3px; } .demo1 input[type='radio']:checked+label:before{ content: "\2022"; color: #fff; font-size: 30px; text-align: center; line-height: 19px; } .demo1 input[type='checkbox']:checked+label:before{ content: "\2713"; font-size: 15px; color: #f3f3f3; text-align: center; line-height: 17px; }
優勢:充分藉助了CSS3的優點,無需使用js和圖片,僅用純CSS3就可搞定java
缺點:兼容性較差,僅支持IE9+css3
js代碼:git
$(function(){ $(".demospan").bind("click",function(){ $(this).addClass("on").siblings().removeClass("on"); }) $(".piaochecked").bind("click",function(){ $(this).hasClass("on_check")?$(this).removeClass("on_check"):$(this).addClass("on_check"); // $(this).toggleClass("on_check"); }) })
css代碼github
.demospan{ display: inline-block; width: 24px; height: 18px; /*float: left;*/ padding-top: 3px; cursor: pointer; text-align: center; margin-right: 10px; background-image: url(http://sandbox.runjs.cn/uploads/rs/161/i5pmsg7s/inputradio.gif); background-repeat: no-repeat; background-position: -24px 0; } .demo21{ opacity: 0; cursor: pointer; -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; filter:alpha(opacity=0); } .on{ background-position: 0 0; } .piaochecked{ display: inline-block; width: 20px; height: 20px; cursor: pointer; margin-left: 10px; text-align: center; background-image: url(http://sandbox.runjs.cn/uploads/rs/161/i5pmsg7s/checkbox_01.gif); background-repeat: no-repeat; background-position: 0 0; } .on_check{ background-position: 0 -21px; } .cbdemo2{ opacity: 0; cursor: pointer; -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=0)"; filter:alpha(opacity=0); }
優勢:兼容性高,支持IE6+web
缺點:使用js+圖片較爲麻煩瀏覽器
/*select*/ .select select{ /*複寫Chrome和Firefox裏面的邊框*/ border:1px solid green; /*清除默認樣式*/ appearance:none; -moz-appearance:none; -webkit-appearance:none; /*在選擇框的最右側中間顯示小箭頭圖片*/ background: url("http://ourjs.github.io/static/2015/arrow.png") no-repeat scroll right center transparent; /*爲下拉小箭頭留出一點位置,避免被文字覆蓋*/ padding-right: 14px; } /*清除ie的默認選擇框樣式清除,隱藏下拉箭頭*/ select::-ms-expand { display: none; }
該方法關鍵在於清除默認樣式,使用css3的appearance屬性,可是兼容性較差,僅支持IE9+。若要兼容低版本瀏覽器,能夠使用Div進行模擬。app
//Todo
兼容更低版本瀏覽器的select樣式修改
最後附上演示連接:修改radio、checkbox和select默認樣式