我正在为我的大学项目制作一个网站,需要 5 个页面。
这是我在主页设置深色模式的代码,但是当我进入第二页时我需要手动按下按钮才能获得深色模式 再次打开,而不是维持主页中的信息。
<img src="DM.png" id="icon">
</div>
<script type="text/javascript">
var icon = document.getElementById("icon");
icon.onclick = function() {
document.body.classList.toggle("darktheme");
if (document.body.classList.contains("darktheme")) {
icon.src="LM.png";
}else
icon.src="dm.png";
}
</script>
最佳答案
localStorage 窗口界面的 localStorage 只读属性允许您访问 Document 来源的 Storage 对象;存储的数据跨浏览器 session 保存。
var icon = document.getElementById("icon");
// on page load event we can use previous theme value
window.onload = function() {
initTheme();
};
function initTheme() {
const theme = localStorage.getItem('theme');
if (theme == 'dark') {
icon.src="LM.png";
} else {
icon.src="dm.png";
}
}
// on icon element click we check the localstorage item 'theme' value to control which theme we should use
icon.onclick = function() {
localStorage.getItem('theme') === 'dark' ? localStorage.setItem('theme', '') : localStorage.setItem('theme', 'dark');
initTheme();
}
关于javascript - 如何跨页面设置深色模式,而不是用户必须在每个页面上手动按下它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72372720/