如果选中,请更改复选框的标签css类
change label css class for checkbox if checked
我有隐藏的复选框。我有图像作为复选框的标签,这样当单击图像时,复选框就会被单击。我正在尝试使其具有不同的不透明性,这取决于是否选中该框。这是我的图片标签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>
您可以简单地使用toggleClass()
。您的代码无法工作,因为the_input
是一个jQuery对象,并且它没有checked
属性。您可以使用.get()
来获取底层DOM元素。
像
the_input.get(0).checked or the_input[0].checked
根据您的代码
$('.checkbox-label').click(function(){
$(this).toggleClass( "checkbox-label-after-click", the_input.get(0).checked ); //You can also use the_input.prop('checked')
});
我猜它在检查检查时会掉下来。当你点击标签时,你最好只是切换类
$('.checkbox-label').click(function(){
$(this).toggleClass( "checkbox-label-after-click" );
});
如果你真的想检查它的状态,你可以这样做:
$('.checkbox-label').click(function(){
var the_input = $(this).next('input');
if(the_input.prop('checked')){
$(this).addClass( "checkbox-label-after-click" );
} else {
$(this).removeClass("checkbox-label-after-click");
}
});
使用the_input.prop('checked')
查看输入是否已检查。它返回一个布尔值。
由于the_input
是一个jquery对象,您不能使用javascript的checked属性,您可以使用the_input[0].checked
或使用prop方法。
替换此:
if(the_input.checked){
有了这个:
if(the_input.prop('checked')){
相关文章:
- Dojo复选框标签
- 将函数事件绑定到更改函数的复选框/标签
- 添加复选框标签中的值
- 隐藏Zend单选按钮和复选框标签在javascript点击处理程序中
- 单击时,添加类,直到复选框/标签单击关闭
- 动态设置复选框标签文本会导致复选框中的样式问题
- ExtJS 2.3:复选框标签上的工具提示
- 意外的空格,而不是不必要的复选框标签
- Android浏览器复选框标签不可点击
- 复选框标签的位置
- 在复选框标签旁边添加文本
- 将复选框标签复制到隐藏文本字段
- 当标记/清除复选框时,引导复选框标签上的工具提示不会隐藏
- 在Javascript中更改复选框标签
- 用于复选框标签的Jquery选择器
- 复选框标签在IE上不起作用
- 使用复选框+标签组合防止双击错误
- 如何获取待选中的复选框标签,并使用数组显示标签
- Jquery通过javascript设置复选框标签的名称
- 清空复选框标签和存储在数据库中的数据