表单:checkbox、radio样式(用图片换掉默认样式)

checkbox、radio样式(用图片换掉默认样式)

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function(){

    //checkbox radio 事件委派
    $(document).on('click', 'input', function(e) {
        var $_this = $(e.target);
        if($_this.is(':checkbox')){
            if ($_this.is(":checked") && $_this.parent(document).is('.checkbox')) {
                $_this.parent(".checkbox").addClass("checked");
            } else {
                $_this.parent(".checkbox").removeClass("checked");
            }
        }
        
        //radio
        if($_this.is(':radio') && $_this.parent(document).is('.checkbox')){
            $(".checkbox input[name=" + $_this.attr("name") + "]").each(function(index, element) {
                if ($(element).is(":checked")) {
                    $(element).parent(".checkbox").addClass("checked");
                } else {
                    $(element).parent(".checkbox").removeClass("checked");
                }
            });
        }
    });

});
</script>
<style type="text/css">
input[type="radio"] { vertical-align: text-bottom; }
input[type="checkbox"] { vertical-align: bottom; *vertical-align: baseline;}
.checkbox { 
    display: inline-block;
    width: 15px;
    height: 15px;
    position: relative;
    background-color: #FFF;
    vertical-align: middle;
    overflow: hidden;
    cursor:pointer;
    background: url(img/icon.png) no-repeat;
    background-position:0 -80px;
}
.checkbox input {
    font-size: 50px;
    padding: 0;
    float: left;
    width: 100px;
    height: 100px;
    display: block;
    cursor: pointer;
    opacity: 0;
    filter: alpha(opacity=0);
}
.checkbox.checked {background-position:0 -40px;}
</style>
</head>
<body>


<form>
<span class="checkbox"><input name="food" type="radio" value="0" /></span>米饭
<span class="checkbox"><input name="food" type="radio" value="10" /></span>馒头
<span class="checkbox checked"><input name="food" type="radio" value="40" checked="checked"/></span>面包

<hr>
<span class="checkbox"><input name="fruit" type="checkbox" value="苹果" /></span>苹果
<span class="checkbox checked"><input name="fruit" type="checkbox" value="橘子" checked="checked"/></span>橘子
<span class="checkbox checked"><input name="fruit" type="checkbox" value="葡萄" checked="checked"/></span>葡萄
<span class="checkbox"><input name="fruit" type="checkbox" value="木瓜" /></span>木瓜
<span class="checkbox"><input name="fruit" type="checkbox" value="菠萝" /></span>菠萝
</form>
</body>
</html>
原文地址:https://www.cnblogs.com/qq21270/p/3501459.html