首页 > 解决方案 > 集成暗模式的系统级设置

问题描述

我需要您的帮助才能集成prefers-color-scheme到我现有的暗模式设置中。

这是我正在使用的 JS:

 <script>
    const switcher = document.querySelector('#switcher');
    const toggleSwitch = document.querySelector('.theme-switch input[type="checkbox"]');

    function setTheme(theme) {
        document.documentElement.setAttribute('data-theme', theme);
        localStorage.setItem('theme', theme);

        const src = 'https://example.com/' + (theme === 'light' ? 'DARK-MODE-1.png' : 'LIGHT-MODE-1.png');
        switcher.setAttribute('src', src);
    }

    const theme = localStorage.getItem('theme') || 'light';
    setTheme(theme);

    toggleSwitch.addEventListener('change', (e) => {
        const theme = e.currentTarget.checked ? 'dark' : 'light';
        setTheme(theme);
    });
    </script>

这是 src="" 从上面的 JS 获取并生成图像路径的 HTML(例如 example.com/DARK-MODE-1.png)。

<label class="theme-switch" for="checkbox">
                    <span title="Click to enable/disable Dark Mode">
                        <img id="switcher" src="">
                    </span>
                    <input type="checkbox" id="checkbox"/>
                </label>

现在我想使用prefers-color-scheme这段代码,所以当用户的系统处于暗模式时,它会自动切换到暗模式。如果用户机器处于光照模式,则应提供光照模式。此外,用户应该能够根据需要切换到任何模式。

感谢您的帮助和您的时间!

标签: javascripthtmlcss

解决方案


“可以在 Javascript 中检测深色模式,方法是使用 window.matchMedia() 检查是否匹配 prefers-color-scheme:深色 CSS 媒体查询。”

let matched = window.matchMedia('(prefers-color-scheme: dark)').matches;

if(matched)
    const theme = 'dark'; //switch to dark theme
else
    const theme = 'light'; //use light theme

window.matchMedia('(prefers-color-scheme: )')接受dark,lightno-preference尽可能的查询。

(通过有用的角度.com

我希望我的回答能帮助你更接近你想要的结果。


推荐阅读