【问题标题】:Integrate system level settings for dark mode集成暗模式的系统级设置
【发布时间】:2021-04-29 23:29:51
【问题描述】:

我需要您的帮助将 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 获取并生成图像路径(例如 example.com/DARK-MODE-1.png)的 HTML。

<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,这样当用户的系统处于暗模式时,它会自动切换到暗模式。如果用户机器处于光照模式,则应提供光照模式。此外,用户应该可以根据需要切换到任何模式。

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

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    “可以通过使用 window.matchMedia() 在 JavaScript 中检测深色模式,以检查 prefers-color-scheme: dark 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: )') 接受 darklightno-preference 作为可能的查询。

    (通过usefulangle.com

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

    【讨论】:

    • 感谢您的回答。这似乎可行,但我不确定应该在代码中的何处添加这些行。你能分享我完整的代码,包括
    • 你可以把上面的代码放在你的函数setTheme中。
    • 我是 JS 的新手,所以想不通。我应该在这一行之后添加它:localStorage.setItem('theme', theme);
    • 非常抱歉,我对 JS 也有点陌生——我帮不上忙,但我可以试试。控制台是否返回任何错误?
    猜你喜欢
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2021-10-24
    相关资源
    最近更新 更多