如何防止网站上的黑暗模式闪烁?

发布于 2025-01-21 17:00:04 字数 856 浏览 2 评论 0 原文

我已经使用这样的简单技术在

<script>

//runs on every page load, checks local storage for last mode and applies dark mode if found
document.body.classList.toggle('dark-mode', localStorage.getItem('darkmode') === 'true');

//the function must be called when dark mode is clicked by the user
function switch_mode(){
    
    const dark = localStorage.getItem('darkmode') === 'true';
    localStorage.setItem('darkmode', !dark);

    const element = document.body;
    element.classList.toggle('dark-mode', !dark);

    }

为了防止闪烁,我尝试将第一行放置在头标签内(通过标题和页脚脚本插件),但似乎不起作用。我已经看到了解决这个问题的解决方案,但是它们似乎都与一开始都不同,因此很难将这些解决方案应用于我使用的代码。

为了触发交换机,我使用的是一个可单击的图标,该图标具有调用该功能的onClick()属性。我的问题有任何解决方案,还是我应该使用其他技术触发器从头开始整个过程​​?

I have implemented a dark mode to a WordPress site using a simple technique like this one found in https://github.com/avecNava/dark-mode.

<script>

//runs on every page load, checks local storage for last mode and applies dark mode if found
document.body.classList.toggle('dark-mode', localStorage.getItem('darkmode') === 'true');

//the function must be called when dark mode is clicked by the user
function switch_mode(){
    
    const dark = localStorage.getItem('darkmode') === 'true';
    localStorage.setItem('darkmode', !dark);

    const element = document.body;
    element.classList.toggle('dark-mode', !dark);

    }

To prevent flickering I've tried to place the first row inside the head tags (via header and footer scripts plugin) but it doesn't seem to work. I've seen solutions to this problem but they all seem to be built different from the start so it's hard to apply those solutions to the code I'm using.

To trigger the switch, I'm using a clickable icon that has an onClick() property that calls the function. Is there any solution to my problem or should I just start the whole thing from scratch using a different technique for example a checkbox trigger?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文