radio,check美化

单选框与复选框原生控件美化有多种解决方案,现在采用经典的input+label的方式自己实现一种

思路:

input 和label 通过id和for属性关联,点击label时,input选中状态改变

透明化input,并且绝对定位,脱离文档流,不影响label空间占用

label包含一个b元素用于模拟单选和复选的框框

使用b元素的伪类,"画出"单选和复选的勾和圆点

利用input:check选择器改变b元素的选中状态

html:

// input控件在前,label在后面
<
input class="input-check" type="checkbox" id="check1" /> <label class="input-check-label" for="check1"><b class="check"></b>复选框</label> <input class="input-check" name="radio1" type="radio" id="radio1" /> <label class="input-check-label" for="radio1"><b class="radio"></b>单选框</label>

css

// 单选与复选框,使用label伪类模拟选框,将关联的原生组件透明
.input-check{
    // 原生控件透明
    position:absolute;
    opacity:0;
}
// 标题
.input-check-label{
    z-index:10;
    cursor:pointer;
    //font-size:14px;
}
// 单选框与复选框的框框 ,是label的子元素
.input-check-label .check, .input-check-label .radio {
    display:inline-block;
    position:relative;
    // 框的高与宽
    height: 1.2em;
    width: 1.2em;
    // 离文字距离
    margin-right: 4px;
    border: 1px solid #999;
    color: #292929;
    background-color: #efefef;
    // 对齐与标题底
    vertical-align:text-bottom;
}
// 单选框是圆形框,
.input-check-label .radio{
    border-radius:50%;
}
// input选中时,切换模拟DOM的选中状态
// input check选中之后,生成复选框选中状态的勾
.input-check:checked + .input-check-label .check:after {
    // 绝对定位于框,左右对齐
    position: absolute;
    left: 0;
    right: 0;
    margin: auto;
    // 勾是一个方形DOM的边框,去掉上边与左边,旋转45度后得到 这里利用伪类after添加空内容做一个边框
    content: '';
    width: 0.7em;
    height: 1em;
    border: 3px solid blue;
    border-top: none;
    border-left: none;
    background: transparent;
    -moz-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
    transform: rotate(45deg);
}
// input-radio 选中之后,生成单选框中的圆点
.input-check:checked + .input-check-label .radio:after {
    // 绝对定位于框,上下左右对齐
    position: absolute;
    left: 0;right: 0;top:0;bottom:0;
    margin: auto;
    // 圆点是圆角边框为50%的DOM
    content: '';
    width: 0.5em;
    height: 0.5em;
    background-color: blue;
    border-radius: 50%;
}

效果截图

原文地址:https://www.cnblogs.com/mirrortom/p/9420752.html