【问题标题】:JavaScript Dark Mode is Affecting My AOS?JavaScript 黑暗模式正在影响我的 AOS?
【发布时间】:2022-12-24 23:50:28
【问题描述】:

你好,这里是新手。

所以我在我的投资组合网站(本地)上工作,我在我的脚本中添加了 AOS(https://michalsnik.github.io/aos/)和暗模式(https://dev.to/ananyaneogi/create-a-dark-light-mode-switch-with-css-variables-34l8)。

在添加黑暗模式之前,动画卷轴起作用了。

添加深色模式后,我的网站在首次加载或刷新时不再自动设置淡入淡出动画。

前任。我的关于我部分在网站加载/刷新时显示;当它应该被隐藏并且只有在滚动时才会淡入。

我该如何解决? (如果没有解决方案我只能忍受这个小错误lmao)

h2 标签上的淡入淡出示例:

<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>

我的 JavaScript 文件:

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);

【问题讨论】:

  • 这是发生在本地还是服务器上?
  • 哎呀忘了说了,这是在本地发生的

标签: javascript aos.js


【解决方案1】:

这是 AOS 的一个常见问题,当您第一次加载网站时,它可能会在更改 css 后发生,在您的情况下,您会触发暗模式。

使用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()
    }
}

【讨论】:

  • 不幸的是,这并没有解决问题?。重新加载页面仍然显示隐藏的 <h2> 标签,只有当我滚动过去并向后滚动时才会淡入/淡出
【解决方案2】:

如果您使用任何一种开关,请尝试一下,

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-15
    • 2020-09-10
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 2020-12-17
    相关资源
    最近更新 更多