简体   繁体   中英

Get CSS properties to use in Rails variables and DB

I'm getting the css attribute when I click on multiple divs named scale-up.

However, I want to store the imported css properties in Rails variables and DB.

The final thing I want is to get the Css properties when I click on them and have them populate the form automatically. This data is stored in a column called color.

The code I tried was:

$(document).ready(function() {
        $(".scale-up-center").click(function() {
            var color = $(".scale-up-center").css("background-color");
            $(".first_scale").css("background-color", color);
        })
    })

I've heard that you can use ajax, but when you look at the guide it's different from what I want.

Main view image

enter image description here

Your approach is a bit brittle. When your css colors are changed, you still have old, invalid colors in your database. Users can also manipulate the form value to inject unwanted colors. You do not have a clean separation of your representation and your logic.

Instead, define some constants in your model for all available colors. Also validate that the passed in value is one of the valid colors:

class Post < ActiveRecord::Base
  COLORS = ["none", "red", "green", "blue"]
  validates :color, inclusion: { in: COLORS }
end

In your view, let the user select the color via a radio-button:

<%= form_for @post do |f| %>
  <%= label :color %>
  <% Post::COLORS.each do |c| %>
    <div class="color-<%= c %>">
      <%= f.radio_button :color, c %> 
    </div>
  <% end %>

  <%= f.submit "Update" %>
<% end %>

Now you can define the representation in your css:

form .color-red {
  background-color: #FF0000;
}

// ...

You can still add some javascript to color your whole text field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM