如何在多页面网站中保留深色/浅色模式状态(HTML/CSS/JS)
解决主题切换后页面跳转恢复默认的问题
你当前的核心问题是主题状态没有持久化存储,页面刷新或跳转后浏览器会重置状态。用浏览器自带的localStorage就能轻松解决——它可以把数据存在本地,同域名下的所有页面都能读取。
修改步骤
- 切换主题时存储状态:点击切换按钮时,除了切换类名,还要把当前主题状态(是否开启
altmode)存到localStorage中。 - 页面加载时恢复主题:页面打开时,先读取
localStorage里的主题状态,再应用对应的样式和图标。
修改后的完整代码
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="styles.css"> </head> <body> <header> <div class="container"> <img src="paint-brush-icon-10-inverted.png" id = "icon" alt="" style="width: 35px; position:relative; top:20px; left: 20px;"> <nav> <ul> <li><a class="navbar" href="home.html">Home</a></li> <li><a class="navbar" href="introduction2.html">Introduction</a></li> <li><a class="navbar" href="experience-education2.html">Experience and education</a></li> <li><a class="navbar" href="portfolio.html">Portfolio</a></li> <li><a class="navbar" href="contactme.html">Contact Me</a></li> </ul> </nav> </div> </header> <hr> <!-- code unimportant here --> <script> var icon = document.getElementById("icon"); // 页面加载时恢复主题状态 window.addEventListener('load', function() { const isAltMode = localStorage.getItem('altmode') === 'true'; if (isAltMode) { document.body.classList.add('altmode'); icon.src = "paint-brush-icon-10.png"; // 避免无profile元素时报错,可根据实际页面调整 if (typeof profile !== 'undefined') { profile.src = "profile-pic (13).png"; } } else { document.body.classList.remove('altmode'); icon.src = "paint-brush-icon-10-inverted.png"; if (typeof profile !== 'undefined') { profile.src = "profile-pic (12).png"; } } }); // 主题切换逻辑 icon.onclick = function(){ document.body.classList.toggle("altmode"); const isAltMode = document.body.classList.contains("altmode"); // 将状态存入localStorage(仅支持字符串,所以转成布尔值的字符串形式) localStorage.setItem('altmode', isAltMode); if(isAltMode){ icon.src = "paint-brush-icon-10.png"; if (typeof profile !== 'undefined') { profile.src = "profile-pic (13).png"; } }else { icon.src = "paint-brush-icon-10-inverted.png"; if (typeof profile !== 'undefined') { profile.src = "profile-pic (12).png"; } } } </script> </body> </html>
关键改动说明
- 新增页面加载监听:页面打开时读取
localStorage中的altmode值,自动应用对应的主题样式和图标,确保跳转后状态一致。 - 主题切换时存储状态:点击按钮时把当前主题的布尔状态转成字符串存入
localStorage,保证状态能被其他页面读取。 - 增加元素存在判断:避免部分页面没有
profile元素时出现控制台报错,可根据自己的页面结构调整或删除这部分判断。
注意:所有需要保持主题一致的页面,都要添加这段脚本逻辑。
内容的提问来源于stack exchange,提问作者callumgilf
相关产品推荐
相关产品推荐

