首页 > web前端 > css教程 > 正文

如何覆盖特定网站的系统'首选颜色方案”设置,并确保一致的用户体验,无论系统的深色模式偏好如何?

Barbara Streisand
发布: 2024-10-26 08:07:30
原创
916 人浏览过

How can you override the system's

覆盖 CSS“prefers-color-scheme”设置

为了适应 macOS、Windows 和 Windows 中深色模式的引入iOS,为Web应用程序实现深色模式至关重要。 Safari、Chrome 和 Firefox 中的本机选项利用 CSS 媒体规则“@media (prefers-color-scheme: dark)”在系统设置为深色模式时自动应用深色模式样式。

但是,这种方法的局限性在于某些用户可能倾向于覆盖特定网站的系统暗模式。此外,Microsoft Edge 目前缺乏对此媒体规则的支持。

解决方案

为了应对这一挑战,全面的解决方案涉及以下内容:

CSS

实现 CSS 变量和主题:

<code class="css">:root {
    --font-color: #000;
    --link-color: #1C75B9;
    --link-white-color: #fff;
    --bg-color: rgb(243,243,243);
}

[data-theme="dark"] {
    --font-color: #c1bfbd;
    --link-color: #0a86da;
    --link-white-color: #c1bfbd;
    --bg-color: #333;
}</code>
登录后复制

然后,在适用的情况下使用这些变量:

<code class="css">body {
    color: #000;
    color: var(--font-color);
    background: rgb(243,243,243);
    background: var(--bg-color);
}</code>
登录后复制

JavaScript

检测用户的首选主题并在浅色和深色模式之间切换:

<code class="javascript">function detectColorScheme(){
    var theme="light";    //default to light

    // Get the theme from local storage, overriding OS settings
    if(localStorage.getItem("theme")){
        if(localStorage.getItem("theme") == "dark"){
            var theme = "dark";
        }
    } else if(!window.matchMedia) {
        // MatchMedia method not supported
        return false;
    } else if(window.matchMedia("(prefers-color-scheme: dark)").matches) {
        // OS theme setting detected as dark
        var theme = "dark";
    }

    // Set document with a `data-theme` attribute if dark theme preferred
    if (theme=="dark") {
         document.documentElement.setAttribute("data-theme", "dark");
    }
}
detectColorScheme();

function switchTheme(e) {
    if (e.target.checked) {
        localStorage.setItem('theme', 'dark');
        document.documentElement.setAttribute('data-theme', 'dark');
        toggleSwitch.checked = true;
    } else {
        localStorage.setItem('theme', 'light');
        document.documentElement.setAttribute('data-theme', 'light');
        toggleSwitch.checked = false;
    }    
}

// Toggle switch listener
const toggleSwitch = document.querySelector('#theme-switch input[type="checkbox"]');
toggleSwitch.addEventListener('change', switchTheme, false);

// Pre-check the dark-theme checkbox if dark-theme is set
if (document.documentElement.getAttribute("data-theme") == "dark"){
    toggleSwitch.checked = true;
}</code>
登录后复制

HTML

包含用于在主题之间切换的复选框:

<code class="html"><label id="theme-switch" class="theme-switch" for="checkbox_theme">
    <input type="checkbox" id="checkbox_theme">
</label></code>
登录后复制

此方法利用 CSS 变量和 JavaScript 自动检测用户的首选主题并动态应用它。它还为用户提供了覆盖特定 Web 应用程序的暗模式设置的灵活性。

以上是如何覆盖特定网站的系统'首选颜色方案”设置,并确保一致的用户体验,无论系统的深色模式偏好如何?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!