【问题标题】:Custom Checkbox Rails / CSS自定义复选框 Rails / CSS
【发布时间】:2019-10-02 14:53:30
【问题描述】:

我希望能够单击标签来检查我的元素而不显示已选中,所以我写了这个:

input[type="checkbox"]
{
   display: none;
 }

但是当我点击它不起作用。仅当元素已在数据库中时才有效。

我必须做 javascript 还是 CSS 可以做?

#views/values/edit.html.erb*

<% @values =["Power", "Independance", "Tradition"] %>
<%= form_for @resultvalue do |f| %>
   <% @values.each do | value | %>
       <%= f.check_box :values, { multiple: true }, value, type:"checkbox" %>
       <%= f.label value %>
   <% end %>
   <%= f.submit%>  
<% end %>
input[type="checkbox"]{
        display: none;
      }
      input[type="checkbox"]+label{
        transition: all 300ms ease;
        font-size: 1.2rem;
        cursor: pointer;
        border-radius: 1rem;
        border: 3px solid white;
        background-color: #0066cc;
        padding: 0.5rem 1rem;
        display: inline-block;
        color: white;

        // Suggested by @zizzo to prevent text selection
        -moz-user-select: -moz-none;
        -khtml-user-select: none;
        -webkit-user-select: none;
        -ms-user-select: none;
        user-select: none;
        // ------------------------


      }
      input[type="checkbox"]:checked+label{
        transition: all 300ms ease;
        background-color:#b70e7e;  
      }

【问题讨论】:

    标签: javascript css ruby-on-rails sass ruby-on-rails-5


    【解决方案1】:

    使用关联复选框的idfor 属性添加到您的标签。这样,点击标签就可以与复选框进行交互。

    <input type="checkbox" id="checkbox1" />
    <label for="checkbox1">Label name</label>
    

    https://stackoverflow.com/a/18432439

    【讨论】:

      【解决方案2】:

      输入标签上没有属性“multiple”,您也不需要设置type: 'checkbox',因为您已经在使用复选框助手,并且您正在传递:values,我认为这没有意义。

      要使标签正确改变复选框状态,您需要正确设置for属性与对应复选框的ID https://developer.mozilla.org/es/docs/Web/HTML/Elemento/label

      您还可以将输入标签嵌套在标签内,这样就不需要for 属性。

      最后,collection_check_boxes 会比你的代码 https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-collection_check_boxes 更干净

      【讨论】:

      • 我不知道如何在我的情况下使用collection_check_boxes,像@arieljuod这样的数组
      • 这有点棘手/hacky,但我想像= f.collection_check_boxes :values, @values, :to_s, :to_s 这样的东西应该可以工作。它将两种方法 (to_s) 应用于集合的每个元素以获取值和标签,调用 to_s 只会为两者返回相同的字符串。
      【解决方案3】:

      我不熟悉 Rails,但我会为复选框分配一个 id 并在标签上使用 for 属性

      <label for="my_input">My input</label>
      <input type="checkbox" id="my_input"/>
      

      或者我会将输入包装在标签中

      <%= f.label value %>
        <%= f.check_box :values, { multiple: true }, value, type:"checkbox" %>
      <% end %>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-18
        • 2016-04-21
        • 2021-11-23
        • 2023-03-05
        • 2013-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多