如何使用純CSS3美化選項按鈕radio的範例程式碼分享

來源:互聯網
上載者:User
這種純CSS3美化選項按鈕radio的方法適用於以下情況:

1、可相容IE9以上,需要相容IE8的要寫IE的hack把樣式去掉

2、只支援選項按鈕radio,因為選項按鈕選中樣式的圓圈可以用CSS做出來,但是複選按鈕checkbox的選中效果對勾就需要圖片或者表徵圖字型庫

3、不需要JS支援轉場效果

是最終:

HTML代碼:


<label for="man" class="radio">    <span class="radio-bg"></span>    <input type="radio" name="sex" id="man" value="男" checked="checked" /> 男    <span class="radio-on"></span></label><label for="woman" class="radio">    <span class="radio-bg"></span>    <input type="radio" name="sex" id="woman" value="女" /> 女    <span class="radio-on"></span></label>

CSS代碼:


.radio{    display: inline-block;    position: relative;    line-height: 18px;    margin-right: 10px;    cursor: pointer;}.radio input{    display: none;}.radio .radio-bg{    display: inline-block;    height: 18px;    width: 18px;    margin-right: 5px;    padding: 0;    background-color: #45bcb8;    border-radius: 100%;    vertical-align: top;    box-shadow: 0 1px 15px rgba(0, 0, 0, 0.1) inset, 0 1px 4px rgba(0, 0, 0, 0.1) inset, 1px -1px 2px rgba(0, 0, 0, 0.1);    cursor: pointer;    transition: all 0.2s ease;}.radio .radio-on{    display: none;}.radio input:checked + span.radio-on{    width: 10px;    height: 10px;    position: absolute;    border-radius: 100%;    background: #FFFFFF;    top: 4px;    left: 4px;    box-shadow: 0 2px 5px 1px rgba(0, 0, 0, 0.3), 0 0 1px rgba(255, 255, 255, 0.4) inset;    background-image: linear-gradient(#ffffff 0, #e7e7e7 100%);    transform: scale(0, 0);    transition: all 0.2s ease;    transform: scale(1, 1);    display: inline-block;}

這個方法中最重要的是選中效果的類名:.radio input:checked + span.radio-on

+是CSS2的偽類,其意義為:p+p 選擇緊接在 <p> 元素之後的所有 <p> 元素。

也就是找到選中的(:checked)的input,其之後的類名為radio-on的span元素做選中圓圈效果。

網上有很多美化方法是把label做成了圓圈,但是這樣的話,單選的文字就必須要要放到label的外面,這導致了點擊文字的時候,不能切換單選效果。

所以我在label裡加了一個類名為radio-bg的span來專門做後面大的圓圈,再用一個類名為radio-on的span來做選中的前面小的圓圈。

這樣就保留了點擊label裡的文字,也可以切換單選的效果。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.