[英]How do I save a CSS class in localstorage?
我有一个 HTML 页面,其中有很多框,我单击每个框我想应用一个新的 CSS class 更改其背景颜色并保存进度。 我正在尝试将这个新的 CSS class 保存在本地存储中,但我做错了。 有人可以帮我吗?
JS代码是:
let box = document.querySelector(".box");
let box_1 = document.querySelector(".box-1");
let box_2 = document.querySelector(".box-2");
const next = document.querySelector(".next");
document.onload=(function(){
var activestate = localStorage.getItem('activestate');
if(activestate !== ''){
box.classList.add('active');
};
});
box_1.addEventListener('click', function(){
box_1.classList.add('active');
box_2.classList.remove('disabled-link');
localStorage.setItem('activestate', 'active');
});
box_2.addEventListener('click', function(){
if (box_1.classList.contains('active')) {
box_2.classList.add('active');
localStorage.setItem('activestate', 'active');
next.style.display = "block";
};
});
这是 Codepen 中的完整代码: https://codepen.io/giuse187/pen/zYLrdMe
您的document.onload
中存在语法错误,您需要创建一个new function(){
而不仅仅是function(){
我建议您使用window.localStorage
而不仅仅是localStorage
所以它会是这样的:
let box = document.querySelector(".box");
let box_1 = document.querySelector(".box-1");
let box_2 = document.querySelector(".box-2");
const next = document.querySelector(".next");
document.onload=(new function(){
var activestate = window.localStorage.getItem('activestate');
if(activestate !== ''){
box.classList.add('active');
};
});
box_1.addEventListener('click', function(){
box_1.classList.add('active');
box_2.classList.remove('disabled-link');
window.localStorage.setItem('activestate', 'active');
});
box_2.addEventListener('click', function(){
if (box_1.classList.contains('active')) {
box_2.classList.add('active');
window.localStorage.setItem('activestate', 'active');
next.style.display = "block";
};
});
jquery... $("正文")。 css("背景色","theColorThatYouNedd");
将“document.onload”替换为“window.addEventListener”
`
window.addEventListener('load', function() {
var activestate = localStorage.getItem('activestate');
if(activestate !== null && activestate !== '') {
box.classList.add('active');
}
});
`
您的onload
function 不正确,这就是您没有得到结果的原因。
使用 window.load 代替 -
window.onload = () => {
// YOUR CODE
};
我建议在 body 元素上使用onload
事件,这是在页面加载时处理事情的推荐方法-
<body onload="checkStorage()">....your elements...</body>
在 Js 方面,这样做 -
function checkStorage() {
var activestate = localStorage.getItem('activestate');
if(activestate !== ''){
box.classList.add('active');
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.