【问题标题】:How to style a label depending on checkbox value? [duplicate]如何根据复选框值设置标签样式? [复制]
【发布时间】:2015-09-09 07:39:04
【问题描述】:

我正在尝试为表单制作一个开/关按钮。按钮的样式取决于复选框的值(选中/未选中)并且复选框本身是隐藏的。我知道您可以使用 css 来管理样式(例如标签按钮的颜色)。有什么办法也可以改变它父母的风格吗?

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_onid。谢谢!

【问题讨论】:

标签: jquery html css ruby-on-rails


【解决方案1】:

如果你稍微改变你的 html,让标签是输入的兄弟(并且就在它之后),即:

<input type="checkbox" id="c1" />
<label for="c1">Some label</label>

仅使用 css 很容易实现,例如:

input[type=checkbox]:not(:checked) + label {color: gray}
input[type=checkbox]:checked + label {color: blue}

【讨论】:

  • 输入是标签的子元素,所以不能只用css选择(css不能选择父元素)
  • 你说得对,这就是为什么我建议更改他的 html 一点。这是一种选择,它会更容易,更防故障。
  • 感谢@TomekSułkowski 的回答!如果我不能在标签中使用“for”怎么办?该应用程序在 RoR 中,我无法设置标签的“for”属性。对不起,我应该说得更清楚。
  • @Quin 这必须在 RoR 中可用,并且它是 html 表单中非常重要的部分。从我在这里看到的apidock.com/rails/ActionView/Helpers/FormTagHelper/label_tag 看来,label_tag 的第一个参数实际上被用作它的for 属性。
  • @TomekSułkowski,是的,我想是的。但是因为它是一个嵌套表单,所以如果我使用它,它会生成一个错误的 id。我还提出了一个label_tag 问题,所以希望我可以使用for 来解决这个问题。
【解决方案2】:

检查加载和每次复选框更改:

var labelStyle = function(elem) {
   var lb = elem.closest('label');
   if (elem.is(':checked')) {
      lb.removeClass('label-unchecked').addClass('label-checked');
   } else {
      lb.removeClass('label-checked').addClass('label-unchecked');
   }
}

$(window).load(function() {
   labelStyle($('#post_images_attributes_0_is_on'));
});

$('#post_images_attributes_0_is_on').on('change', function() {
   labelStyle($(this));
});

【讨论】:

  • 您没有考虑在页面渲染时(由后端)设置复选框的可能性
猜你喜欢
  • 1970-01-01
  • 2017-02-18
  • 2023-02-13
  • 1970-01-01
  • 1970-01-01
  • 2014-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多