譯者 | 布加迪
審校 | 重樓
近年來,暗模式作為用戶界面選項備受追捧。它提供了更暗的背景和更亮的文本,不僅可以減輕眼睛疲勞,還可以節(jié)省電池續(xù)航時間,尤其是在OLED屏幕上。
為了實施暗模式,您將使用CSS定義外觀。然后,您將使用JavaScript來處理暗模式和亮模式之間的切換。
為每個主題使用一個類,這樣您就可以在兩種模式之間輕松切換。對于較完整的項目而言,您應(yīng)該考慮暗模式會如何影響設(shè)計的方方面面。
.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)類之間切換。注意,改變切換開關(guān)以表明當(dāng)前模式也是個好主意。該代碼使用CSS過濾器來實現(xiàn)這一功能。
// 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);
這使得您的頁面可以通過點(diǎn)擊切換容器來更改主題。
考慮以下兩個改進(jìn),可以使您的暗模式網(wǎng)站被訪客更易于使用。
這需要在網(wǎng)站加載之前檢查用戶的系統(tǒng)主題,并調(diào)整您的網(wǎng)站進(jìn)行匹配。下面介紹如何使用matchMedia函數(shù)來做到這一點(diǎn):
// 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();
現(xiàn)在,任何訪問您網(wǎng)站的用戶都會看到一個與他們設(shè)備的當(dāng)前主題相匹配的設(shè)計。
為了進(jìn)一步增強(qiáng)用戶體驗,可以使用本地存儲記住用戶所選擇的模式。這確保了他們在面對會話時不必重復(fù)選擇偏愛的模式。
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"); }
暗模式不僅限于外觀,而是把用戶的舒適和偏好放在第一位。如果遵循這種方法,您可以創(chuàng)建對用戶友好的界面,鼓勵訪客重復(fù)訪問。您在編程和設(shè)計時,應(yīng)優(yōu)先考慮用戶便利,并為訪客提供更好的數(shù)字體驗。
原文標(biāo)題:How to Implement Dark Mode Using CSS and JS,作者:DAVID JAJA
本文鏈接:http://www.www897cc.com/showinfo-26-12700-0.html如何使用CSS和JavaScript實施暗模式?
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。郵件:2376512515@qq.com