首页 > 解决方案 > 刷新切换开关无法在暗模式设置中进行任何更改

问题描述

当我刷新页面并且该切换处于暗模式时,我的主题仍然很亮。当我切换到亮模式然后再次切换到暗模式时,它会变为暗模式。我尝试设置 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);

标签: javascriptdomlocal-storagedarkmode

解决方案


推荐阅读