Javascript 如何通过单击按钮为每个页面设置相同的背景图像?
我有几个按钮,每个按钮都会改变背景。但问题是,它并不是每页都有描述,我必须一直点击这些按钮重置背景。 Application.html.erbJavascript 如何通过单击按钮为每个页面设置相同的背景图像?,javascript,jquery,css,ruby-on-rails,Javascript,Jquery,Css,Ruby On Rails,我有几个按钮,每个按钮都会改变背景。但问题是,它并不是每页都有描述,我必须一直点击这些按钮重置背景。 Application.html.erb <button type="button" onclick="changeBackground('paper')" color="black">Black</button> <button type="button" onclick="changeBackground"('gray')">Gray</button
<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>
黑色
如果您试图让用户在页面上设置不同的视觉主题,则可以将cookie与class属性一起使用
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
现在,让我们设置javascript以处理不断变化的主题:
<button class="change-theme" data-theme="theme-1">Classic</button>
<button class="change-theme" data-theme="theme-2">Funky fresh</button>
这可能看起来很复杂,但实际上是正确的方法:
- HTML只是内容
- 样式表处理表示
- Javascript增强行为
见:
除了打字错误,没有理由在任何页面上都不起作用。您是否在这些页面上正确地包含了脚本?检查控制台是否有错误?将背景图像url存储为cookie,以便可以在网站的多个html页面上读取--
body.theme-1 {
background-color: 'red';
}
body.theme-2 {
background-color: 'blue';
}
<button class="change-theme" data-theme="theme-1">Classic</button>
<button class="change-theme" data-theme="theme-2">Funky fresh</button>
$(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;
});