gpt4 book ai didi

javascript - 如何使用 Javascript 保存 CSS 更改?

转载 作者:太空宇宙 更新时间:2023-11-04 01:24:34 25 4
gpt4 key购买 nike

我创建了一个页面,人们可以在其中使用 javascript 自行更改背景。但是当我在页面之间切换时,设置消失了。如何仅使用“HTML”、“CSS”和“JAVASCRIPT”来解决这个问题?

这是我的 html 代码:

<input type="image" id="bc-wood-button" src="images/background-wood.jpg" width="213" height="120">
<input type="image" id="bc-nature-button" src="images/background-nature.jpg" width="213" height="120">

这是我的 Javascript:

$(document).ready(function() {
$('body').css('background-image', 'url("images/background-wood.jpg")');
document.getElementById("bc-wood-button").addEventListener("click", WoodenBackground);
document.getElementById("bc-nature-button").addEventListener("click", NatureBackground);

function WoodenBackground() {
$('body').css('background-image', 'url("images/background-wood.jpg")');
}

function NatureBackground() {
$('body').css('background-image', 'url("images/background-nature.jpg")');
}
});

最佳答案

正如评论中的其他建议,您可以使用 localStoragesessionStorage 来保存和加载数据。

$(document).ready(function()
{
// ulrs of some existing backgrounds
var backgrounds = {
wood: "https://images.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.walldevil.com%2Fwallpapers%2Fa81%2Fwallpapers-dragon-art-yellow-artistic-silver-images-backgrounds-nature-abstract-background-desktop-cool.jpg&f=1",
nature: "https://images.duckduckgo.com/iu/?u=https%3A%2F%2Fimage.freepik.com%2Ffree-photo%2Fnature-design-with-bokeh-effect_1048-1882.jpg&f=1"
};

var settings = loadSettings();
setBackground(settings.background);

document.getElementById("bc-wood-button").addEventListener("click", WoodenBackground);
document.getElementById("bc-nature-button").addEventListener("click", NatureBackground);

function setBackground(background) {
$('body').css('background-image', 'url("'+background+'")');
localStorage.setItem("settings.background", background);
}

function WoodenBackground() {
setBackground(backgrounds.wood);
}

function NatureBackground()
{
setBackground(backgrounds.nature);
}

function loadSettings()
{
var background = localStorage.getItem("settings.background");
// at first run there is no data, also user may anytime clear storage
if (!background)
{
background = backgrounds.wood;
}
return { background: background }
}
});

jsfiddle

关于javascript - 如何使用 Javascript 保存 CSS 更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48349997/

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