我不相信这个问题是重复的,我已经阅读了纯CSS复选框图像替换,我正在从 http://www.hongkiat.com/blog/css3-checkbox-radio/中获取代码
我的问题是我不想为我的复选框使用 ID,因为这是一个模板,许多可能包含在同一页面上。我几乎已经让一切正常,但我无法选择标签:之前,当选中复选框将其更改为不同的背景颜色时。
.HTML
<label><input type="checkbox" /></label>
CSS(最后一个选择器是我正在尝试工作的那个)
input[type="checkbox"] {
display:none;
}
label {
display: inline-block;
cursor:pointer;
position:relative;
font-size:13px;
top:0;
right:-30px;
width:16px;
}
label:before {
content: "";
display:inline-block;
width:16px;
height:16px;
margin-right:10px;
position:absolute;
left:0;
bottom:1px;
background-color:#aaa;
}
input[type="checkbox"]:checked + label:before {
content:"";
background:#219161;
margin-right:10px;
position:absolute;
left:0;
bottom:1px;
height:16px;
width:16px;
display:inline-block;
padding:0 0 0 0;
}
您可以在label
内但在input
之后添加一个额外的范围,并在其上使用伪元素
label {
display: inline-block;
cursor: pointer;
position: relative;
font-size: 13px;
top: 0;
right: -30px;
width: 16px;
}
label span:before {
content: "";
display: inline-block;
width: 16px;
height: 16px;
margin-right: 10px;
position: absolute;
left: 0;
bottom: 1px;
background-color: #aaa;
}
input[type="checkbox"]:checked + span:before {
content: "";
background: #219161;
margin-right: 10px;
position: absolute;
left: 0;
bottom: 1px;
height: 16px;
width: 16px;
display: inline-block;
padding: 0 0 0 0;
}
<label>
<input type="checkbox" /><span></span>
</label>
JS解决方案供参考,CSS答案在我发布后出现并留待将来参考
HTML (加载到一个模板 ID 为 thisTemplateID 的div 中)
<label><input type="checkbox" class="checkboxtype1" /></label>
.JS
$('#' + thisTemplateID + " .checkboxtype1").bind('change', function() {
if ( $( this ).prop("checked") ) {
$(this).parent('label').addClass('ticked');
} else {
$(this).parent('label').removeClass('ticked');
}
});
.CSS
label {
display: inline-block;
cursor:pointer;
position:relative;
font-size:13px;
top:0;
right:-30px;
width:16px;
}
label:before {
content: "";
display:inline-block;
width:16px;
height:16px;
margin-right:10px;
position:absolute;
left:0;
bottom:1px;
background-color:#aaa;
}
label.ticked:before {
content:"";
background:#219161;
margin-right:10px;
position:absolute;
left:0;
bottom:1px;
height:16px;
width:16px;
display:inline-block;
padding:0 0 0 0;
}