譯者 | 布加迪
審校 | 重樓
近年來,暗模式作為用戶界面選項備受追捧。它提供了更暗的背景和更亮的文本,不僅可以減輕眼睛疲勞,還可以節省電池續航時間,尤其是在OLED屏幕上。
為了實施暗模式,您將使用CSS定義外觀。然后,您將使用JavaScript來處理暗模式和亮模式之間的切換。
為每個主題使用一個類,這樣您就可以在兩種模式之間輕松切換。對于較完整的項目而言,您應該考慮暗模式會如何影響設計的方方面面。
.dark { background: #1f1f1f; color: #fff; } .light { background: #fff; color: #333; }
將以下JavaScript添加到script.js文件中。第一部分代碼只是選擇用于處理切換的元素。
// Get a reference to the theme switcher element and the document body const themeToggle = document.getElementById("theme__switcher"); const bodyEl = document.body;
下一步,使用下列JavaScript在亮模式(light)類與暗模式(dark)類之間切換。注意,改變切換開關以表明當前模式也是個好主意。該代碼使用CSS過濾器來實現這一功能。
// Function to set the theme function setTheme(theme) { // If the theme is "dark," add the "dark" class, remove "light" class, // and adjust filter style bodyEl.classList.toggle("dark", theme === "dark"); // If the theme is "light," add the "light" class, remove "dark" class, bodyEl.classList.toggle("light", theme !== "dark"); // adjust filter of the toggle switch themeToggle.style.filter = theme === "dark" ? "invert(75%)" : "none"; } // Function to toggle the theme between light and dark function toggleTheme() { setTheme(bodyEl.classList.contains("dark") ? "light" : "dark"); } themeToggle.addEventListener("click", toggleTheme);
這使得您的頁面可以通過點擊切換容器來更改主題。
考慮以下兩個改進,可以使您的暗模式網站被訪客更易于使用。
這需要在網站加載之前檢查用戶的系統主題,并調整您的網站進行匹配。下面介紹如何使用matchMedia函數來做到這一點:
// Function to detect user's preferred theme function detectPreferredTheme() { // Check if the user prefers a dark color scheme using media queries const prefersDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches; setTheme(prefersDarkMode); } // Run the function to detect the user's preferred theme detectPreferredTheme();
現在,任何訪問您網站的用戶都會看到一個與他們設備的當前主題相匹配的設計。
為了進一步增強用戶體驗,可以使用本地存儲記住用戶所選擇的模式。這確保了他們在面對會話時不必重復選擇偏愛的模式。
function setTheme(theme) { bodyEl.classList.toggle("dark", theme === "dark"); bodyEl.classList.toggle("light", theme !== "dark"); themeToggle.style.filter = theme === "dark" ? "invert(75%)" : "none"; // Setting the theme in local storage localStorage.setItem("theme", theme); } // Check if the theme is stored in local storage const storedTheme = localStorage.getItem("theme"); if (storedTheme) { setTheme(storedTheme); } function detectPreferredTheme() { const prefersDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches; // Getting the value from local storage const storedTheme = localStorage.getItem("theme"); setTheme(prefersDarkMode && storedTheme !== "light" ? "dark" : "light"); }
暗模式不僅限于外觀,而是把用戶的舒適和偏好放在第一位。如果遵循這種方法,您可以創建對用戶友好的界面,鼓勵訪客重復訪問。您在編程和設計時,應優先考慮用戶便利,并為訪客提供更好的數字體驗。
原文標題:How to Implement Dark Mode Using CSS and JS,作者:DAVID JAJA
本文鏈接:http://www.www897cc.com/showinfo-26-12700-0.html如何使用CSS和JavaScript實施暗模式?
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com