javascript - 刷新切换开关无法在暗模式设置中进行任何更改
问题描述
当我刷新页面并且该切换处于暗模式时,我的主题仍然很亮。当我切换到亮模式然后再次切换到暗模式时,它会变为暗模式。我尝试设置 localstorage 值,但不知道为什么它不起作用。这是我的脚本文件。
const toggleSwitch = document.querySelector('input[type="checkbox"]');
const nav = document.getElementById('nav');
const toggleicon = document.getElementById('toggle-icon');
const image1 = document.getElementById('image1');
const image2 = document.getElementById('image2');
const image3 = document.getElementById('image3');
function imageSetup(mode){
image1.src = `svg/undraw_Coding_re_iv62_${mode}.svg`;
image2.src = `svg/undraw_Landscape_mode_re_r964_${mode}.svg`;
image3.src = `svg/undraw_Loading_re_5axr_${mode}.svg`;
}
function darkMode(){
nav.style.backgroundColor = 'rgb(0 0 0 / 50%)';
toggleicon.children[0].textContent = "Dark Mode";
toggleicon.children[1].classList.replace('fa-sun', 'fa-moon');
imageSetup('light');
};
function lightMode(){
nav.style.backgroundColor = 'rgb(255 255 255 / 50%)';
toggleicon.children[0].textContent = "Light Mode";
toggleicon.children[1].classList.replace('fa-moon', 'fa-sun');
imageSetup('dark');
}
function switchToDarkMode(input){
if (input.target.checked){
document.documentElement.setAttribute('data-theme', 'dark');
localStorage.setItem('mode', 'dark');
}else {
document.documentElement.setAttribute('data-theme', 'light');
localStorage.setItem('mode', 'light');
}
finalMode();
}
function finalMode(){
if(localStorage.getItem('mode') === 'dark'){
darkMode();
} else{
lightMode();
};
}
toggleSwitch.addEventListener('change', switchToDarkMode);
解决方案
推荐阅读
- python - 如何访问许多已创建的行中的一行
- javascript - 为什么动画没有像预期的那样将盒子放在底部
- android - 在当前主题错误中找不到样式“bottomNavigationStyle”
- node.js - 如何将 JSON 格式的 MongoDB 集合导出到本地系统?
- javascript - 在 JSON.stringify 将循环结构转换为 json 的 TypeError (
) - ios - MKMapView 有警告(VKBuildingFootprintTileSource)
- python - f = open_input_file("sample", "rb") 中的断言错误:
- java - 日期年份值在无效时显示有效
- javascript - 动态创建的元素
- php - 在 wordpress/PHP 中使用 fputs() 将 ISO 8859-1 字符串写入文件