【问题标题】:How can I set the same background-image for every page with a button click?如何通过单击按钮为每个页面设置相同的背景图像?
【发布时间】:2016-02-13 13:10:08
【问题描述】:

我有几个按钮,每个按钮都会改变一个背景。但问题是它并没有在每一页上都有描述,我必须一直点击这些按钮来重置背景。 Application.html.erb

<button type="button" onclick="changeBackground('paper')" color="black">Black</button>
<button type="button" onclick="changeBackground"('gray')">Gray</button>

<script>

function myFunction(color) {
        if (color == "paper"){
         $('body').css('background-image', 'some image')
        }
        if (color == "gray"){
         $('body').css('background-image', 'some image')
     }
   }
</script>

这些背景仅适用于一页。如何为每个页面设置一次背景?谢谢!

【问题讨论】:

  • 除了错别字之外,没有理由这在任何页面上都不起作用。您是否在这些页面上正确包含了脚本?检查控制台是否有错误?
  • 将背景图片 url 存储为 cookie,以便您的网站可以在多个 html 页面上读取它 -- github.com/js-cookie/js-cookie

标签: javascript jquery css ruby-on-rails


【解决方案1】:

如果您想要让用户在页面上设置不同的视觉主题,您可以使用 cookie 和类属性。

module ThemingHelper
  def theme_class
    classes = []
    # lets check if the cookie is acceptable first:
    if ["theme-1", "theme-2"].include?(cookies[:theme])
      classes << cookies[:theme]
    end
    classes.join(" ").html_safe
  end
end

layouts.html.erb:

# ...
<body class="<%= theme_class %>">
# ...

application.css:

body.theme-1 {
  background-color: 'red';
}

body.theme-2 {
  background-color: 'blue';
}

现在让我们设置 javascript 来处理不断变化的主题:

<button class="change-theme" data-theme="theme-1">Classic</button>
<button class="change-theme" data-theme="theme-2">Funky fresh</button>

请注意,我们不使用内联处理程序。它是一个不好的做法,用 jQuery 很容易避免。

$(document).on('click', '.change-theme', function(){
  var theme = $(this).data('theme');
  document.cookie = "theme=" + theme;
  $(body).removeClass("theme-1 theme-2").addClass(theme);
  return false;
});

这可能看起来很复杂,但实际上是正确的做法:

  • HTML 只是内容
  • 样式表处理表示
  • Javascript 增强行为

见:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    相关资源
    最近更新 更多