修改radio、checkbox、select默認樣式的方法


現在前端頁面效果日益豐富,默認的input組件樣式顯然已經不能滿足需求。趁着這次開發的頁面中有這方面的需求,在這里整理一下修改radiocheckboxselect的方法。
首先上效果圖:

enter description here

radio and checkbox

修改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就可搞定

  • 缺點:兼容性較差,僅支持IE9+

js+圖片

  • js代碼:

$(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代碼

.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+

  • 缺點:使用js+圖片較為麻煩

select

/*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進行模擬。

Todo

  • 兼容更低版本瀏覽器的select樣式修改

最后附上演示鏈接:修改radio、checkbox和select默認樣式


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM