简体   繁体   中英

JavaScript Dark Mode is Affecting My AOS?

hello, newbie here.

So I'm working on my portfolio website(local) and I've added AOS( https://michalsnik.github.io/aos/ ) and a dark mode( https://dev.to/ananyaneogi/create-a-dark-light-mode-switch-with-css-variables-34l8 ) in my scripts.

Before adding the dark mode, the animated scrolls worked.

After I added the dark mode, my website no longer animates the fades automatically when it's first loaded or when it's refreshed.

Ex. My About Me section is shown when the site is loaded/refreshed; when it should have been hidden and only fades in when scrolled into.

How do I fix this? (if there's no solution I can just live with this minor bug lmao)

Example of the fade on the h2 tag:

<div data-aos="fade-right" data-aos-duration="1000" data-aos-easing="ease-in-out"
     data-aos-mirror="true" data-aos-once="false" class="aos-init aos-animate">
     <h2>About Me</h2>
</div>

My JavaScript file:

 document.addEventListener("DOMContentLoaded", function() { setTimeout(function() { AOS.refresh(); }, 500); }); // Dark Mode Switcher // Source: https://dev.to/ananyaneogi/create-a-dark-light-mode-switch-with-css-variables-34l8 var toggleSwitch = document.querySelector('.theme-switch input[type="checkbox"]'); const currentTheme = localStorage.getItem('theme'); if (currentTheme) { document.documentElement.setAttribute('data-theme', currentTheme); if (currentTheme === 'dark') { toggleSwitch.checked = true; } } function switchTheme(e) { if (e.target.checked) { document.documentElement.setAttribute('data-theme', 'dark'); localStorage.setItem('theme', 'dark'); } else { document.documentElement.setAttribute('data-theme', 'light'); localStorage.setItem('theme', 'light'); } } window.addEventListener('load', AOS.refresh) toggleSwitch.addEventListener('change', switchTheme, false);

It is a common issue of AOS, when you first load a website it may happen after a change in css, in your case when your trigger dark mode.

try forcing the page to reload after you change to dark mode with window.location.reload()

function switchTheme(e) {
    if (e.target.checked) {
        document.documentElement.setAttribute('data-theme', 'dark');
        localStorage.setItem('theme', 'dark');
        window.location.reload()

    }
    else {
        document.documentElement.setAttribute('data-theme', 'light');
        localStorage.setItem('theme', 'light');
        window.location.reload()
    }
}

If you use any kind of switch then try it,

             <DarkModeSwitch
              className={darkMode ? 'dark__icon' : 'light__icon'}
              checked={darkMode}
              onClick={() => toggleTheme() + window.location.reload()}
              />
           

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM