巧用CSS3伪类选择器自定义checkbox和radio的样式

因为原生的checkbox和radio的样式太简陋了,在设计页面的时候,设计师每每会设计本身的checkbox和radio样式。一半状况下,为了适应各个浏览器的兼容性,咱们都会用其余的元素替代原生的checkbox和radio,而后用js实现选中和未选中时候的样式,用来模拟checkbox和radio。css

例如这种:html

用其余元素模拟(以checkbox为例):浏览器

<div class='checkbox'></div>
$('.checkbox').click(function(){
    if($(this).hasClass("checked")){
              $(this).removeClass("checked");
    }else{
             $(this).addClass("checked");
    }
});

运用JS添加点击事件,切换选中和未选中的状态。this

那么,能仅仅只用样式,改变原生的checkbox的样式呢?spa

 

使用CSS实现:设计


在表单元素中,为了扩大checkbox的点击范围,咱们常常用label和checkbox相连,如今也能够运用这个关系,把样式加在label上,隐藏checkbox(设置透明度,不能display:none,不然关联会失效)。code

html结构:htm

<input type="checkbox" id="mycheck" />
<lable for="mycheck">check me</label>

 

css样式:blog

input[type="checkbox"] + label::before {
content: '\a0'; /* non-break space */
display: inline-block;
vertical-align: .2em;
width: .8em;
height: .8em;
margin-right: .2em;
border-radius: .2em;
background: silver;
text-indent: .15em;
line-height: .65;
}

 

利用伪元素::before给label添加样式,利用CSS3的伪类选择器:checked,:hover,:focus,:disabled设置不用状态的样式事件

 

input[type="checkbox"]:checked + label::before {
content: '\2713';
background: yellowgreen;
}

 

input[type="checkbox"]:focus + label::before {
box-shadow: 0 0 .1em .1em #58a;
}
input[type="checkbox"]:disabled + label::before {
background: gray;
box-shadow: none;
color: #555;
}

 

 

这样,仅仅使用样式就能显示不一样状态下的checkbox样式了。

相关文章
相关标签/搜索