Javascript 使用cookie更改背景图像

Javascript 使用cookie更改背景图像,javascript,cookies,background,Javascript,Cookies,Background,我正在寻找帮助,将cookie放入此脚本中,以便浏览器在关闭或更改页面时记住所选的背景图像。任何帮助都将不胜感激 函数changeTheme() { var e=document.getElementById(“主题”); var theme=e.options[e.selectedIndex].value; console.log(主题); document.getElementById(“shelf”).style.backgroundImage=“url”(“+theme+”); }

我正在寻找帮助,将cookie放入此脚本中,以便浏览器在关闭或更改页面时记住所选的背景图像。任何帮助都将不胜感激

函数changeTheme()
{
var e=document.getElementById(“主题”);
var theme=e.options[e.selectedIndex].value;
console.log(主题);
document.getElementById(“shelf”).style.backgroundImage=“url”(“+theme+”);
}

违约
心
世俗的
向日葵
蒙廷

看起来您唯一缺少的是cookie的设置和获取。下面是一篇关于使用jquery和javascript的文章

这是jquery,但它完成了任务

<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<!--download jquery.cookie from here http://plugins.jquery.com/cookie -->
<script type="text/javascript" src="images/jquery.cookie.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    var theme = $.cookie("backgroundImage");
    if (theme){document.getElementById("shelf").style.backgroundImage = "url("+theme+")";}
    $("#themes").change(function() {
        theme = $(this).val();
        $.cookie("backgroundImage", theme);
        document.getElementById("shelf").style.backgroundImage = "url("+theme+")";
    });
});
</script>
</head>
<body id="shelf">
<!--<select id="themes" onChange="changeTheme()" name="ChangeBG">-->
<select id="themes" name="ChangeBG">
  <option value="images/background1.jpg" selected="selected">Default</option>
  <option value="images/background2.jpg">Heart</option>
  <option value="images/background3.jpg">Earthly</option>
  <option value="images/background4.jpg">Sunflowers</option>
  <option value="images/background5.jpg">Mountin</option>
</select>
</body>
</html>

$(文档).ready(函数(){
var主题=$.cookie(“背景图像”);
if(theme){document.getElementById(“shelf”).style.backgroundImage=“url”(“+theme+”);}
$(“#主题”).change(函数(){
theme=$(this.val();
$.cookie(“背景图像”,主题);
document.getElementById(“shelf”).style.backgroundImage=“url”(“+theme+”);
});
});
违约
心
世俗的
向日葵
蒙廷

谢谢您的帮助!当浏览器保持打开状态时,这非常有效,但当您关闭浏览器时,图像会变回默认值这是我正在使用的CSS,有没有办法从Cookie中加载CSS背景图像?正文{margin:auto;Background color:#000000;Background image:url(“images/background1.jpg”);文本渲染:优化易读性;-webkit字体平滑:抗锯齿;颜色:#fff;最小宽度:0;位置:绝对;顶部:0px;右侧:0px;底部:0px;左侧:0px;背景大小:封面;背景位置:50%顶部;背景重复:无重复;背景附件:固定;宽度:自动;高度:自动;}是的,谢谢我这么做了,我已经读到我需要添加一个持久的cookie,直到它的生存时间已经过去。不是会话cookie,我看不出我可以在哪里设置过期时间长度?因此,一旦浏览器关闭,它就不会重置。此外,IE仅在cookie有过期日期时才会保留cookie