gpt4 book ai didi

javascript - 使用 cookie 更改背景图像

转载 作者:行者123 更新时间:2023-12-03 11:24:38 25 4
gpt4 key购买 nike

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

function changeTheme()
{

var e = document.getElementById("themes");
var theme = e.options[e.selectedIndex].value;
console.log(theme);
document.getElementById("shelf").style.backgroundImage = "url("+theme+")";

}
<body id="shelf">
<select id="themes" onChange="changeTheme()" 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>

最佳答案

看起来您唯一缺少的部分是 cookie 的设置和获取。这是一篇关于setting and getting cookies的帖子同时使用 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>

关于javascript - 使用 cookie 更改背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26973852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com