如何读取Storage属性并编写if条件语句实现主题背景切换?
解决localStorage主题判断的条件逻辑问题
你当前的代码存在逻辑顺序问题,应该先从localStorage读取theme值,再进行条件判断,而非在if代码块内才获取值。以下是修正后的完整代码:
function whiteSet() { // 先获取localStorage中存储的theme值 const theme = localStorage.getItem('theme'); // 条件判断:当theme值严格等于'aluminum'时执行对应逻辑 if (theme === 'aluminum') { document.getElementById("headerbar").style.backgroundImage = "url(images/themes/aluminum.png)"; } else { document.getElementById("headerbar").style.backgroundImage = "url(images/themes/galaxy.png)"; } }
逻辑说明
- 先通过
localStorage.getItem('theme')获取存储的主题值,避免重复读取存储 - 条件
theme === 'aluminum'直接判断值是否匹配,同时能覆盖theme不存在(值为null)的场景,此时会自动进入else块使用默认的银河主题
内容的提问来源于stack exchange,提问作者Slender Tech
相关产品推荐
相关产品推荐

