[英]How can I save CSS changes with Javascript?
I created a page where people can change te background by them self with javascript. 我创建了一个页面,人们可以在其中使用javascript自行更改背景。 But when I swap between pages, the setting is gone.
但是当我在页面之间交换时,设置消失了。 How can I fix that WITH ONLY: "HTML", "CSS" and "JAVASCRIPT"?
如何仅使用“ HTML”,“ CSS”和“ JAVASCRIPT”修复该问题?
This is my html code: 这是我的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">
And this is my Javascript: 这是我的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")');
}
});
As other suggested in comments you can use localStorage
or sessionStorage
to save and load data. 如注释中的其他建议,您可以使用
localStorage
或sessionStorage
来保存和加载数据。
$(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 }
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.