使用simple_form更改复选框图标

时间:2016-07-11 13:55:58

标签: ruby-on-rails sass simple-form

我是铁杆和网络应用的新手,如果有人可以提供帮助,我将不胜感激。 使用simple_form并尝试更改复选框图标图像,但css(scss)似乎无法正常工作。 代码如下。

<div class="col-md-6">
   <%= f.input :is_something, as: :boolean, input_html: { class: 'custom-check-box' } %>
</div>

生成代码

<div class="col-md-6">
  <div class="input boolean optional test_is_somethiing"><input value="0" type="hidden" name="test[is_something]" /><label class="boolean optional checkbox" for="test_is_somethiing"><input class="boolean optional custom-check-box" type="checkbox" value="1" checked="checked" name="test[is_something]" id="test_is_somethiing" />Label</label></div>
</div>

SCSS是

.custom-check-box {
   opacity: 0;
   vertical-align: middle;
   input[type=checkbox] + label:after {
     opacity: 1;
     display: inline-block;
     background: image-url('check_box_off.png');
     background-repeat: no-repeat;
     vertical-align: middle;
     background-size: 50%;
     cursor: pointer;
     &:checked + label:after {
       opacity: 1;
       display: inline-block;
       background-size: 50%;
       background: image-url('check_box_on.png');
       background-repeat: no-repeat;
       vertical-align: middle;
       cursor: pointer;
     }
   }
 }

1 个答案:

答案 0 :(得分:1)

你遗漏了一些让它工作的事情。

在您的HTML中,您需要<label>标记for="" attr,就像这样;

<div>
  <input id="custom-checkbox" class="custom-check-box" type="checkbox" />
  <label for="custom-checkbox"></label>
</div>

attr的标签需要与复选框的id匹配

然后将您的scss更改input[type=checkbox] + label:after改为& + label:after,就像这样;

.custom-check-box {
   display: none;
   vertical-align: middle;

   & + label:after {
     content: '';
     padding: 16px;
     display: inline-block;
     background: image-url('check_box_off.png');
     background-repeat: no-repeat;
     vertical-align: middle;
     background-size: 50%;
     cursor: pointer; 
   }

   &:checked + label:after {
     background: image-url('check_box_on.png');
   }

 }

您的:after伪也需要内容attr才能使用。

I created a codepen for you