【问题标题】:Keep user selected background throughout all the pages on the site在网站上的所有页面中保持用户选择的背景
【发布时间】:2014-10-27 15:45:54
【问题描述】:

需要帮助。 我为页面制作了一个背景选择器,所以基本上有 4 种不同的背景图片可供用户选择。

这是我为此使用的代码和脚本:

HTML:

<ul>
  <li id="color-1"></li>
  <li id="color-2"></li>
  <li id="color-3"></li>
  <li id="color-4"></li>
</ul>

脚本:

<script>
    $('ul li').click(function() {
    var background = $(this).css('background-image');
    $("html, body").css("background-image", background);
});
</script>

问题是当我切换页面时,背景图像会重置为默认图像。 我知道这可以通过设置 cookie 来解决。我尝试了几种方法,但都没有奏效。

谁能帮我解决这个问题。 谢谢你。

【问题讨论】:

  • 你真的尝试过使用cookies吗?

标签: javascript html css cookies background-image


【解决方案1】:

选中后,将背景存储在localStorage中

<script>
    $('ul li').click(function() {
    var background = $(this).css('background-image');
    $("html, body").css("background-image", background);
    localStorage.background = background;
});
</script>

加载页面时,应用它。

$("html, body").css("background-image", localStorage.background);

【讨论】:

  • 我最终使用了这个代码 sn-p。它适用于所有主页面和子页面。也适用于我测试的所有浏览器。非常感谢您的帮助!
【解决方案2】:

将背景变量保存在 cookie 中:

document.cookie = "bgimage=" + background;

然后获取cookie:

$(function(){
   var bgCookie = getCookie("bgimage");
   $("html, body").css("background-image", bgCookie);
});

function getCookie(name) {
  var parts = document.cookie.split(name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}

getCookie() 方法取自:Get cookie by name

【讨论】:

  • 这适用于主页,但是当我添加子页面(在子文件夹中)时,它搞砸了。也根本没有在 Opera 中工作。但是谢谢你的帖子。
【解决方案3】:

您可以将 custom-background.js 插件添加到您的网站

https://github.com/CybrSys/custom-background.js

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多