原理:大致原理都是使用原生的checkbox或input標(biāo)簽低淡,在其后面設(shè)置相關(guān)聯(lián)的label元素姓言。給<input>元素設(shè)置為透明,然后通過定位讓用戶看到的是<label>元素蔗蹋,利用css的原生屬性來判斷用戶的操作何荚,設(shè)置選中后的label樣式,即input[type=checkbox]:checked+label{}
利用css3偽元素實(shí)現(xiàn)樣式修改
html代碼
<p>您的性別:</p>
<div class="radio-sex">
<input type="radio" id="sex1" name="sex">
<label for="sex1"></label>
<span>男</span>
</div>
<div class="radio-sex">
<input type="radio" id="sex2" name="sex">
<label for="sex2"></label> 女
</div>
CSS樣式
.radio-sex {
position: relative;
display: inline-block;
margin-right: 12px;
}
.radio-sex input {
vertical-align: middle;
margin-top: -2px;
margin-bottom: 1px;
/* 前面三行代碼是為了讓radio單選按鈕與文字對齊 */
width: 20px;
height: 20px;
appearance: none;/*清楚默認(rèn)樣式*/
-webkit-appearance: none;
opacity: 0;
outline: none;
/* 注意不能設(shè)置為display:none*/
}
.radio-sex label {
position: absolute;
left: 0;
top: 0;
z-index: -1;
/*注意層級(jí)關(guān)系,如果不把label層級(jí)設(shè)為最低猪杭,會(huì)遮擋住input而不能單選*/
width: 20px;
height: 20px;
border: 1px solid #3582E9;
border-radius: 100%;
}
.radio-sex input:checked+label {
background: #3582E9;
}
.radio-sex input:checked+label::after {
content: "";
position: absolute;
left: 8px;
top: 2px;
width: 5px;
height: 12px;
border-right: 1px solid #fff;
border-bottom: 1px solid #fff;
transform: rotate(45deg);
}
優(yōu)點(diǎn):充分借助了CSS3的優(yōu)勢餐塘,無需使用js和圖片,僅用純CSS3就可搞定
缺點(diǎn):兼容性較差胁孙,僅支持IE9+
案例:
利用圖片實(shí)現(xiàn)樣式修改
實(shí)現(xiàn)思路
1.設(shè)置input 屬性hidden對該input進(jìn)行隱藏
<input type="radio" name="type" id="adviceRadio1" value="1" checked hidden/>
2.借助label for標(biāo)簽通過id綁定input 唠倦,這樣在點(diǎn)擊label時(shí)實(shí)際就是點(diǎn)擊了input
<input type="radio" name="type" id="adviceRadio1" value="1" checked hidden/>
<label for="adviceRadio1" class="advice"></label>
3.定義label的樣式称鳞,設(shè)置未選中狀態(tài)的背景圖
.advice{
height: 12px;
width: 12px;
display: inline-block;
background-image: url('https://caiyunupload.b0.upaiyun.com/newweb/imgs/icon-unchecked.png');
background-repeat: no-repeat;
background-position: center;
vertical-align: middle;
margin-top: -4px;
}
4.使用相鄰選擇器設(shè)置選中狀態(tài)label的樣式
input[type="radio"]:checked + .advice{
background-image: url('https://caiyunupload.b0.upaiyun.com/newweb/imgs/icon-checked.png');
}
以上是radio單選框的實(shí)現(xiàn)代碼,checkbox也是類似 將input type定義成checkbox即可
利用插件實(shí)現(xiàn)
awesome-bootstrap-checkbox插件
awesome-bootstrap-checkbox是一款可以美化Bootstrap復(fù)選框和單選按鈕的插件稠鼻。它使用純CSS編寫冈止,沒有任何的javascript文件。它通過在原生Bootstrap組件的基礎(chǔ)上做一些小改動(dòng)候齿,即可完成漂亮的美化效果熙暴。
演示地址:http://awesome-bootstrap-chec...
插件下載:https://www.bootcdn.cn/awesom...
注:需要引入awesome-bootstrap-checkbox.css、font-awesome.css以及font awesome對應(yīng)的字體font文件
pretty.css
pretty.css是一款純css3漂亮的checkbox和radio美化效果慌盯。pretty.css可以和多種字體圖標(biāo)結(jié)合使用周霉,對原生的checkbox和radio進(jìn)行美化,還可以制作按鈕點(diǎn)擊時(shí)的動(dòng)畫效果亚皂。
演示地址:http://www.htmleaf.com/Demo/2...
插件下載:https://www.bootcdn.cn/pretty...