1. 程式人生 > >5分鐘DIY一個自定義單選框單選按鈕

5分鐘DIY一個自定義單選框單選按鈕

轉眼間2017年了,在這裡祝大家2017都能 展翅高飛心想事成
這裡寫圖片描述

上次寫博已經是兩個月前了,這兩個月七搞八搞學了不少黑科技日後必會分享給大家~下面咱們就開門見山了

由於瀏覽器本身自帶的單選按鈕且不說好看不好看,各大瀏覽器廠商也是一人一個樣兒想要統一效果相對來說比較麻煩,所以我們常見的做法就是 自定義 一個單選按鈕。像這樣的效果:

這裡寫圖片描述

這樣的一個性別選擇按鈕非常的常見,類似的效果也都可以用這種方法寫出來。

.rdo {
    width: 20px;
    height: 0px;
    background-color: #000;
    margin-right: 30px;
    border-radius
: 50%; position: relative; } .rdo:before,.rdo:after { content: ''; display: block; position: absolute; border-radius: 50%; transition: .3s ease; } .rdo:before { top: 0px; left: 0px; width: 18px; height: 18px; background-color: #fff; border: 1px solid #000; } .
rdo:after { top: 6px; left: 6px; width: 8px; height: 8px; background-color: #fff; } .rdo:checked:after { top: 4px; left: 4px; width: 12px; height: 12px; background-color:#ea879a; } .rdo:checked:before { border-color:#ea879a; } <input type="radio" class=
"rdo" name="sex" checked> <input type="radio" class="rdo" name="sex">

沒錯,這裡就是全部程式碼了,就是這麼簡單!如果你看懂了的話是不是感覺so easy?哈哈~

假如你沒看懂也沒關係,我們來一點點看。

1.在html結構中新增兩個普通的單選按鈕

<input type="radio" class="rdo" name="sex" checked>
<input type="radio" class="rdo" name="sex">

這裡寫圖片描述

2.設定input的樣式,將寬高任意一個設為0,全為0也可以

.rdo {
    width: 20px;
    height: 0px;
    background-color: #000;
    margin-right: 30px;
    border-radius: 50%;
    position: relative;
}


3. 利用beforeafter偽元素自定義單選按鈕的樣式

.rdo:before,.rdo:after {
    content: '';
    display: block;
    position: absolute;
    border-radius: 50%;
    transition: .3s ease;
}
.rdo:before {
    top: 0px;
    left: 0px;
    width: 18px;
    height: 18px;
    background-color: #fff;
    border: 1px solid #000;
}
.rdo:after {
    top: 6px;
    left: 6px;
    width: 8px;
    height: 8px;
    background-color: #fff; 
}

這裡寫圖片描述


4. 當單選按鈕被選中時改變被選中按鈕身上before和after偽元素的樣式,如上圖中所示(圖畫得賊醜∩_∩,見諒)

.rdo:checked:after {
    top: 4px;
    left: 4px;
    width: 12px;
    height: 12px;
    background-color:#ea879a; 
}
.rdo:checked:before {
    border-color:#ea879a; 
}


如果朋友們有什麼更好的辦法模擬單選按鈕效果歡迎留言探討^_^



所有部落格已轉移至個人部落格地址www.clramw.top