首頁  >  文章  >  web前端  >  如何覆蓋特定網站的系統「首選顏色方案」設置,並確保一致的使用者體驗,無論系統的深色模式偏好如何?

如何覆蓋特定網站的系統「首選顏色方案」設置,並確保一致的使用者體驗,無論系統的深色模式偏好如何?

Barbara Streisand
Barbara Streisand原創
2024-10-26 08:07:30917瀏覽

How can you override the system's

覆蓋CSS「prefers-color-scheme」設定

為了適應macOS、Windows 和Windows 中macOS、WindowsiOS,為深色模式的引入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>

實現CSS 變量和主題:
<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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn