如何使用CSS和JavaScript實(shí)施暗模式?
譯文譯者 | 布加迪
審校 | 重樓
近年來(lái),暗模式作為用戶(hù)界面選項(xiàng)備受追捧。它提供了更暗的背景和更亮的文本,不僅可以減輕眼睛疲勞,還可以節(jié)省電池續(xù)航時(shí)間,尤其是在OLED屏幕上。

不妨了解如何結(jié)合使用CSS和JavaScript為網(wǎng)站和Web應(yīng)用程序添加暗模式選項(xiàng)。
了解暗模式
暗模式是您網(wǎng)站的另一種配色方案,將傳統(tǒng)的淺色背景換成深色背景。它使您的頁(yè)面更悅目,尤其在光線(xiàn)較暗的情況下。由于對(duì)用戶(hù)友好,暗模式已經(jīng)成為許多網(wǎng)站和應(yīng)用程序的標(biāo)準(zhǔn)功能。
搭建項(xiàng)目
在實(shí)施暗模式之前,確保您已搭建了一個(gè)項(xiàng)目,準(zhǔn)備好進(jìn)行工作。您應(yīng)該以一種結(jié)構(gòu)化的方式組織HTML、CSS和JavaScript文件。
HTML代碼
從頁(yè)面內(nèi)容的以下標(biāo)記開(kāi)始入手。訪(fǎng)客將能夠使用theme__switcher元素在暗模式和亮模式之間切換。
<body>
   		     <nav class="navbar">
 			           <span class="logo">Company Logo</span>
                        <ul class="nav__lists">
                                <li>About</li>
                               <li>Blog</li>
                                <li>Contact</li>
                         </ul>
                         <div id="theme__switcher">
                                  <img id="theme__image" src="./toggle.svg" alt="" />
                          </div>
               </nav>
    <main>
Lorem ipsum dolor sit amet consectetur adipisicing elit.
    Odit deserunt sit neque in labore quis quisquam expedita minus
    perferendis.
    </main>
    <script src="./script.js"></script>
</body>CSS代碼
添加以下CSS代碼來(lái)設(shè)置示例的樣式。這將充當(dāng)默認(rèn)的亮模式,稍后您可以為暗模式視圖添加新樣式。
@import url("https://fonts.googleapis.com/css2?family=Quicksand:wght@400;700&display=swap");
* {
         margin: 0;
         padding: 0;
         box-sizing: border-box;
}
html { font-size: 62.5%; }
body { font-family: "Quicksand", sans-serif; }
.navbar {
         display: flex;
         padding: 2rem;
         font-size: 1.6rem;
         align-items: center;
         color: rgb(176, 58, 46);
         background-color: #fdedec;
}
.navbar span { margin-right: auto; }
.logo { font-weight: 700; }
.nav__lists {
         display: flex;
         list-style: none;
         column-gap: 2rem;
        margin: 0 2rem;
}
#theme__switcher { cursor: pointer; }
main {
        width: 300px;
         margin: 5rem auto;
         font-size: 2rem;
         line-height: 2;
         padding: 1rem 2rem;
         border-radius: 10px;
         box-shadow: 2px 3.5px 5px rgba(242, 215, 213, 0.4);
}現(xiàn)在,您的界面應(yīng)該是這樣:

使用CSS和JavaScript實(shí)施暗模式
為了實(shí)施暗模式,您將使用CSS定義外觀。然后,您將使用JavaScript來(lái)處理暗模式和亮模式之間的切換。
創(chuàng)建主題類(lèi)
為每個(gè)主題使用一個(gè)類(lèi),這樣您就可以在兩種模式之間輕松切換。對(duì)于較完整的項(xiàng)目而言,您應(yīng)該考慮暗模式會(huì)如何影響設(shè)計(jì)的方方面面。
.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)類(lèi)與暗模式(dark)類(lèi)之間切換。注意,改變切換開(kāi)關(guān)以表明當(dāng)前模式也是個(gè)好主意。該代碼使用CSS過(guò)濾器來(lái)實(shí)現(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);這使得您的頁(yè)面可以通過(guò)點(diǎn)擊切換容器來(lái)更改主題。

使用JavaScript增強(qiáng)暗模式
考慮以下兩個(gè)改進(jìn),可以使您的暗模式網(wǎng)站被訪(fǎng)客更易于使用。
檢測(cè)用戶(hù)偏好
這需要在網(wǎng)站加載之前檢查用戶(hù)的系統(tǒng)主題,并調(diào)整您的網(wǎng)站進(jìn)行匹配。下面介紹如何使用matchMedia函數(shù)來(lái)做到這一點(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)在,任何訪(fǎng)問(wèn)您網(wǎng)站的用戶(hù)都會(huì)看到一個(gè)與他們?cè)O(shè)備的當(dāng)前主題相匹配的設(shè)計(jì)。
使用本地存儲(chǔ)持久化用戶(hù)首選項(xiàng)
為了進(jìn)一步增強(qiáng)用戶(hù)體驗(yàn),可以使用本地存儲(chǔ)記住用戶(hù)所選擇的模式。這確保了他們在面對(duì)會(huì)話(huà)時(shí)不必重復(fù)選擇偏愛(ài)的模式。
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");
  }擁抱以用戶(hù)為中心的設(shè)計(jì)
暗模式不僅限于外觀,而是把用戶(hù)的舒適和偏好放在第一位。如果遵循這種方法,您可以創(chuàng)建對(duì)用戶(hù)友好的界面,鼓勵(lì)訪(fǎng)客重復(fù)訪(fǎng)問(wèn)。您在編程和設(shè)計(jì)時(shí),應(yīng)優(yōu)先考慮用戶(hù)便利,并為訪(fǎng)客提供更好的數(shù)字體驗(yàn)。
原文標(biāo)題:How to Implement Dark Mode Using CSS and JS,作者:DAVID JAJA















 
 
 











 
 
 
 