css实现自定义checkbox、radio样式

纯css实现自定义checkbox、radio样式,兼容ie浏览器

chrome浏览器下效果图:


ie浏览器下效果图:


html代码:

<!-- 需要引入jQuery -->
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<input type="checkbox" class="my-checkbox"/>
<input type="checkbox" class="my-checkbox"/>
<br/>
<input type="radio" class="my-radio" name="type"/>
<input type="radio" class="my-radio" name="type"/>

js代码:


/**
 * 委托点击事件
 */
$(document).on('click','.my-checkbox+span,.my-radio+span',function(e){
    var input=$(this).prev('input');
    //触发点击事件
    input.trigger('click');
    return false;
});
/**
 * 自定义样式代替原生input样式,在input后增加span标签
 */
function addSpanAfterInput(input){
    
    input.after('<span></span>');
	
    //给span设置样式(位置样式)和原input相同
    input.each(function(index,ele){
        var styles = {};
        var input = $(ele);
        styles.float = input.css('float');
        styles.margin = input.css('margin');
        styles.position = input.css('position');
        if(input.css('position')=='absolute'){
            styles.top = input.css('top');
            styles.bottom = input.css('bottom');
            styles.left = input.css('left');
            styles.right = input.css('right');
        }
        input.next('span').css(styles);
        styles=null;
    });
}
//页面加载完就给自定义input按钮添加span伪类和样式
var myCB = $('.my-checkbox,.my-radio');
addSpanAfterInput(myCB);

css样式:

.my-checkbox,.my-radio {
    display: none;
}
.my-checkbox:checked+span,.my-radio:checked+span {
    border: 1px solid #333;
}

.my-checkbox+span {
    width: 14px;
    height: 14px;
    font-size: 14px;
    display: inline-block;
    border: 1px solid #333;
    position: relative!important;
    cursor: pointer;
}
.my-radio+span {
    display: inline-block;
    width: 14px;
    height: 14px;
    vertical-align: middle;
    border-radius: 50%;
    border: 1px solid #333;
    position: relative!important;
    cursor: pointer;
}

.my-checkbox:checked+span:after {
    width: 100%;
    height: 100%;
    line-height: 100%;
    font-size: 100%;
    text-align: center;
    content: '\2714';
    color: #fff;
    background-color: #333;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}
.my-radio:checked+span::after {
    border-radius: 50%;
    width: 8px;
    height: 8px;
    line-height: 8px;
    content: ' ';
    background: #000;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}

优点:

1.用法简单,设置类名my-checkbox、my-radio即可使用。

2.性能好,选中样式使用css定义,比使用背景图切换更简单。

缺点:

动态生成的checkbox和radio需要调用addSpanAfterInput方法生成用于显示的span元素

如有改进方案,欢迎在下方留言。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值