如何根据复选框的值设置标签样式? [英] How to style a label depending on checkbox value?
问题描述
我正在尝试为表单创建一个开/关按钮.按钮的样式取决于复选框的值(已选中/未选中),并且复选框本身是隐藏的.我知道您可以使用CSS来控制样式(如标签按钮的颜色).有什么办法可以改变父母的风格吗?
I am trying to make a on/off button for a form. The button's style depends on the checkbox's value (checked/not-checked) and the checkbox itself is hidden. I know you can use css to govern the style (like the label button's colour). Is there any way I can also change its parents' style?
HAML(RoR):
HAML (RoR):
%label.primary_btn
set as primary
= f.check_box :is_on, style: 'display:none;'
HTML:
<label class="primary_btn">
On/Off Button
<input name="post[images_attributes][0][is_on]" type="hidden" value="0"><input id="post_images_attributes_0_is_on" style="display:none;" type="checkbox" value="1">
</label>
CSS:
.primary_btn {
float: left;
clear: both;
padding: 6px 10px;
border-top-left-radius: 9px;
border-top-right-radius: 9px;
border-bottom-right-radius: 9px;
border-bottom-left-radius: 9px;
color: white;
box-shadow: black 0px 1px 4px -1px;
cursor: pointer;
background-color: #6d6d6d;
}
附加评论:
我不能在标签中使用'for',因为我无法调用嵌套字段:is_on
的id
.谢谢!
Addition comment:
I can't use 'for' in label because I cannot call the id
of the nested field :is_on
. Thanks!
推荐答案
如果稍微更改html,以使标签是输入的同级(紧随其后),即:
If you change your html a bit, so that the label is a sibling of an input (and just after it), i.e.:
<input type="checkbox" id="c1" />
<label for="c1">Some label</label>
仅使用CSS即可轻松实现,例如:
it's easy to achieve with css only, e.g.:
input[type=checkbox]:not(:checked) + label {color: gray}
input[type=checkbox]:checked + label {color: blue}
这篇关于如何根据复选框的值设置标签样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!