【问题标题】:How do I change a background image according to a selection?如何根据选择更改背景图像?
【发布时间】:2014-11-19 07:23:23
【问题描述】:

所以,我有一个类别模型,有几个整数可供选择,即:

category.rb

class Category < ActiveRecord::Base
  belongs_to :quote
  belongs_to :subscriber

  CATEGORY_TYPE = {
    1 => "Food",
    2 => "Fun",
    3 => 'Cats',
  }

end

查看代码:

<div class="landing-bg2 size">
<div class="styled email-input2">
    <%= form_for @subscriber do |f| %>
    <% if @subscriber.errors.any? %>
      <div class="errorExplanation" style="color: white;">
      <h2><%= pluralize(@subscriber.errors.count, 'error') %> encountered with your email:</h2>
      <ul>
      <% @subscriber.errors.full_messages.each do |m| %>
      <li><%= m %></li>
     <% end %>
     </ul>
     </div>
  <% end %>
  <%= f.fields_for :subscriber, @subscriber.build_category do |cat| %>
  <%= cat.select(:category_type, Category::CATEGORY_TYPE.map{|p| [p[1], p[0]]}, {prompt: 'Please select'}, {class: 'styled email-input2'}) %>
  <% end %>
</div>

</div>

  <div class="col-xs-12 col-md-12 email-input" style="text-align: center;">
  <p>
  <%= f.text_field :email, placeholder: "Enter your email", class: "email-input"  %>
  </p>

  </div>
  </div>

  <div class="get_quotes">
     <%= f.submit "Get quotes", class: "get_quotes btn-danger" %>
    <% end %>
  </div>
</div<

例如,当访问者点击猫时,我希望背景图像变为猫,而当他们点击食物时,我希望背景变为食物图​​像。

我该如何做到这一点?如您所见,整个视图页面被包裹在一个landing-bg2 类中。

对应的css是:

.landing-bg2 {
    background: asset-url("303342.jpg") no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;

}

请指教! :)

【问题讨论】:

    标签: html ruby-on-rails css ruby-on-rails-4


    【解决方案1】:

    使用一些jquery 来改变这样的背景图片

    $(document).ready(function(){
       $("#cat_category_type).change(function(){
          var value = $(this).val();
          if(value == "cats")
          {
             $('.landing-bg2').style.css = "background: asset-url('cats.jpg') no-repeat center center fixed;"
           }
          if(value=="dogs")
          {
             $('.landing-bg2').style.css = "background: asset-url('dogs.jpg') no-repeat center center fixed;"
          }
      etc.....
       })
    })
    

    【讨论】:

    • 谢谢@Choco,我刚试过,但它似乎不起作用:(你能仔细检查一下 JQuery 代码,看看它是否正常
    • @SonnyBlack 我刚刚添加了一些示例代码,根据您的要求更改您的 ID
    • 我做了,看起来代码缺少 ;或者什么嗯。有任何想法吗?谢谢!
    • @SonnyBlack 您现在可以添加您的原始 jquery 代码吗
    • @SonnyBlack 当我们应用背景图像样式时,引号放错了位置。我已经编辑了我的答案一次检查它
    猜你喜欢
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    相关资源
    最近更新 更多