我有隐藏的复选框。我有图像作为复选框的标签,因此当单击图像时,复选框也会被单击。我正在尝试使图像具有不同的不透明度,具体取决于是否选中该框。这是我的图像标签的 CSS:
.checkbox-label{
opacity: .2;
}
.checkbox-label:hover{
opacity: .5;
}
.checkbox-label-after-click{
opacity: 1;
}
这是我用来移动类的javascript
<script>
$('.checkbox-label').click(function(){
var the_input = $(this).next('input');
if(the_input.checked){
$(this).addClass( "checkbox-label-after-click" );
} else {
$(this).removeClass("checkbox-label-after-click");
}
});
</script>
基本上,当有人点击标签时,它应该获取下一个输入,即复选框,标签的类应该改变。我还尝试切换 addClass 和 removeClass 方法,这使得类切换在第一次点击时起作用,但之后就没有了。
这是 html:
我如何让它工作?
最佳答案
我会用纯 CSS 来做到这一点,就像这样:
label {
cursor: pointer;
}
/* Change cursor when the label is hovered */
input[type=checkbox] {
display: none;
}
/* Hide the ugly default radio styling */
label > span {
opacity: 0.2;
}
/* Hide the checkmark by default */
input[type=checkbox]:checked + span {
opacity: 1;
color: green;
}
/* Show the checkmark when the radio is checked */
<label>
<input type="checkbox" name="obvious"><span>✓</span> I look good.</label>
<br/>
<label>
<input type="checkbox" name="obvious"><span>✓</span> Cause we've been re-styled!</label>
<br/>
<label>
<input type="checkbox" name="obvious"><span>✓</span> I've got a green checkmark if you click me.</label>
<br/>
<label>
<input type="checkbox" name="obvious"><span>✓</span> We are a family of checkmarks!</label>
关于javascript - 如果选中,更改复选框的标签 css 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28385014/