检查 LocalStorage 中的项目是否为 null 并且是否正在更改背景
Check if a item in LocalStorage is null and isint changing backgrounds
我做了一个配置页面,当我按下一个按钮时,它会改变背景,颜色或图像,我创建了 localStorages img 和颜色,我的问题是当它们同时不为空时时间,而不是背景去图像它去用“颜色”制作背景,我正在尝试的代码是这样的:
if (localStorage.getItem("Color") === null) { //if Color is null
if (localStorage.getItem("img") === null) {// And Image too
document.body.style.backgroundImage = "url('css/Images/Instruments/pexels-pixabay-459797.jpg')"; // a image appear in the background
} else { // else if Color is null but img isint
document.body.style.backgroundImage = localStorage.getItem("img"); //load the image in the background
}
// THIS IS My problem: i dont know how to check if both arent null
if(localStorage.getItem("Color") !== 'null' localStorage.getItem("img") !== 'null'){ //If Both arent null
document.body.style.backgroundImage = localStorage.getItem("img"); // load the Image not the background
}
}};
您可以使用逻辑运算符 &&,如下所示:
if (!localStorage.getItem('color') {
if (!localStorage.getItem('img') {
document.body.style.backgroundImage = 'url("your image url")';
} else {
document.body.style.backgroundImage = localStorage.getItem('img');
}
if (localStorage.getItem('color') && localStorage.getItem('img') {
document.body.style.backgroundImage = localStorage.getItem('img');
}
}
我做了一个配置页面,当我按下一个按钮时,它会改变背景,颜色或图像,我创建了 localStorages img 和颜色,我的问题是当它们同时不为空时时间,而不是背景去图像它去用“颜色”制作背景,我正在尝试的代码是这样的:
if (localStorage.getItem("Color") === null) { //if Color is null
if (localStorage.getItem("img") === null) {// And Image too
document.body.style.backgroundImage = "url('css/Images/Instruments/pexels-pixabay-459797.jpg')"; // a image appear in the background
} else { // else if Color is null but img isint
document.body.style.backgroundImage = localStorage.getItem("img"); //load the image in the background
}
// THIS IS My problem: i dont know how to check if both arent null
if(localStorage.getItem("Color") !== 'null' localStorage.getItem("img") !== 'null'){ //If Both arent null
document.body.style.backgroundImage = localStorage.getItem("img"); // load the Image not the background
}
}};
您可以使用逻辑运算符 &&,如下所示:
if (!localStorage.getItem('color') {
if (!localStorage.getItem('img') {
document.body.style.backgroundImage = 'url("your image url")';
} else {
document.body.style.backgroundImage = localStorage.getItem('img');
}
if (localStorage.getItem('color') && localStorage.getItem('img') {
document.body.style.backgroundImage = localStorage.getItem('img');
}
}