如何使用sessionStorage在JavaScript中保持css样式的更改



我正在尝试制作一个按钮,在block和none之间切换CSS显示属性。我正试图让用户打开和关闭背景色,然后在页面之间移动时保留选择。更尴尬的是,我只能使用内联CSS和香草JavaScript来完成这项工作。

到目前为止,我已经设法切换了display属性,但我不知道如何实现sessionStorage。我尝试过无数种不同的方式。下面的例子是我最近的一次尝试。

任何帮助都将不胜感激:(

<div onchange="colours()" id='red' width='100%' height='auto' style="background-color:red; padding: 20%; display:block;">

</div>
<button  id="button" style='font-size: 200px;'>test</button>
var e = document.getElementById('red');
() => {
if (sessionStorage.getItem('divColor') === '1'){
e.style.display = "none";
}
else{
e.style.display = "block";
}
}

document.getElementById('button').addEventListener('click', function() {
if (e.style.display === 'block') { 
e.style.display = 'none';
sessionStorage.setItem("divColor", 1);
} else { 
e.style.display = 'block';
}
});

您可以使用cookie存储:说明:更改功能中的背景后,将其保存在cookie中并设置cookie过期日期,过期日期可能是一天或任何时间,如果没有提示客户端更改页面背景,则始终检查是否设置了cookie,并且一旦设置了cookie,则使用cookie中存储的颜色值来设置页面背景,一旦浏览器存储了cookie,它就会一直可用,我认为这是在网站上做这种事情的更好方法。希望这个解释对有用

我解决了我的问题!这花了整个周末的时间,但我做到了(我是JS的新手,所以小胜利意义重大(。

<button id="button" style="padding: 20px";>test</button>

<p id="text" style="font-size:200px; padding: 0; margin: 0; text-transform: uppercase; background-color:red;">change me</p>
var button = document.getElementById('button');
var text = document.getElementById('text');
var key = sessionStorage.getItem ('key');
var obj = JSON.parse(key);

if (key)
{text.style.background = obj};
button.addEventListener('click', textChange);
function textChange (test) {
if (text.style.backgroundColor === 'red') {
text.style.backgroundColor = 'blue';
sessionStorage.setItem ('key', JSON.stringify (text.style.backgroundColor));
} else {
text.style.backgroundColor = 'red';
sessionStorage.removeItem ('key');
} 
}

最新更新