复选框作为网页中比较常见的一个组件,有的时候我们需要对它进行美化,但是我们无法直接为其定义样式,所以我们需要一些其它的办法。
表单元素中有label
元素和 for
属性,当我们点击label
标签时,对应的表单元素就会有所反应。我们就是依据这个特性来实现的。
html:
<body>
<input type="checkbox" id="myCheck">
<label for="myCheck"></label>
</body>
- 1
- 2
- 3
- 4
既然是自定义,我们就要把label
伪装成复选框的样子,比较常见的是方框状,所以我们就有了如下的CSS样式。
#myCheck + label{
background-color: white;
border-radius: 5px;
border:1px solid #d3d3d3;
width:20px;
height:20px;
display: inline-block;
text-align: center;
vertical-align: middle;
line-height: 20px;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
这样我们就为label
元素定义为圆角的正方形边框,然后就需要根据复选框的状态进行相应的样式调整。
#myCheck:checked + label{
background-color: #eee;
}
#myCheck:checked + label:after{
content:"\2714";
}
- 1
- 2
- 3
- 4
- 5
- 6
上述代码分别为label
元素定义了复选框选中状态时应具有的样式,比如背景色变灰、而且添加了“√”,\2714就是相应的编码。
这样我们就大功告成了,但是别忘了,我们要将自带的checkbox
定义为display:none;
这样就可以隐藏自带的复选框了。
效果图(不要忘记将原来的设为隐藏,这里为展示效果):
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
我们在项目中使用到input标签的checkbox的时候,它的默认样式通常无法满足项目需求,主要是它显得有点小而丑。将它根据项目的需求进行改造就是我们要做的事情了,下面讲两种常用的做法。
1.使用背景图片代替选中效果
主要原理就是将原来的checkbox隐藏:visibility: hidden属性但它依然占据位置,用图片代替它的位置。
优点就是兼容性好
效果图:
代码:
--html--
<div id="check">
<span><input type="checkbox"class="input_check" id="check1"><label for="check1"></label></span>
<span><input type="checkbox"class="input_check" id="check2"><label for="check2"></label></span>
</div>
- 1
- 2
- 3
- 4
- 5
--css--
#check {margin: 20px auto;}
#check .input_check {position: absolute;width: 20px;height: 20px;visibility: hidden;background: #E92333;}
#check span {position: relative;}
#check .input_check+label {display: inline-block;width: 20px;height: 20px;background: url('入驻申请页面3/入驻申请页面/images/gou.png') no-repeat;background-position: -31px -3px;border: 1px solid skyblue;}
#check .input_check:checked+label {background-position: -7px -4px;}
- 1
- 2
- 3
- 4
- 5
- 6
2.使用css3实现
主要是利用after,缺点是存在兼容性问题。
效果
--html--
<div id="check_css3">
<span><input type="checkbox"class="input_check" id="check3"><label for="check3"></label></span>
<span><input type="checkbox"class="input_check" id="check4"><label for="check4"></label></span>
</div>
- 1
- 2
- 3
- 4
- 5
--css--
#check_css3 {margin: 20px auto;}
#check_css3 span {position: relative;}
#check_css3 .input_check {position: absolute;visibility: hidden;}
#check_css3 .input_check+label {display: inline-block;width: 16px;height: 16px;border: 1px solid #ffd900;}
#check_css3 .input_check:checked+label:after {content: "";position: absolute;left: 2px;bottom: 12px;width: 9px;height: 4px; border: 2px solid #e92333;border-top-color: transparent;border-right-color: transparent; -ms-transform: rotate(-60deg); -moz-transform: rotate(-60deg); -webkit-transform: rotate(-60deg); transform: rotate(-45deg);}
- 1
- 2
- 3
- 4
- 5
- 6
以上是两种实现方法的介绍,如果你有更好更快捷的方法。 Tell me please.