如何覆蓋特定網站的系統「首選顏色方案」設置,並確保一致的使用者體驗,無論系統的深色模式偏好如何?
覆蓋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>
登入後複製
以上是如何覆蓋特定網站的系統「首選顏色方案」設置,並確保一致的使用者體驗,無論系統的深色模式偏好如何?的詳細內容。更多資訊請關注PHP中文網其他相關文章!
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章
Windows 11 KB5054979中的新功能以及如何解決更新問題
4 週前
By DDD
如何修復KB5055523無法在Windows 11中安裝?
3 週前
By DDD
Inzoi:如何申請學校和大學
4 週前
By DDD
如何修復KB5055518無法在Windows 10中安裝?
3 週前
By DDD
在哪裡可以找到Atomfall中的站點辦公室鑰匙
4 週前
By DDD

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)