• 使用CSS和JavaScript实现系统夜晚护眼模式效果
  • 发布于 2个月前
  • 212 热度
    0 评论
近年来,暗模式作为用户界面选项备受追捧。它提供了更暗的背景和更亮的文本,不仅可以减轻眼睛疲劳,还可以节省电池续航时间,尤其是在OLED屏幕上。不妨了解如何结合使用CSS和JavaScript为网站和Web应用程序添加暗模式选项。

了解暗模式
暗模式是您网站的另一种配色方案,将传统的浅色背景换成深色背景。它使您的页面更悦目,尤其在光线较暗的情况下。由于对用户友好,暗模式已经成为许多网站和应用程序的标准功能。

搭建项目
在实施暗模式之前,确保您已搭建了一个项目,准备好进行工作。您应该以一种结构化的方式组织HTML、CSS和JavaScript文件。

HTML代码
从页面内容的以下标记开始入手。访客将能够使用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代码来设置示例的样式。这将充当默认的亮模式,稍后您可以为暗模式视图添加新样式。
@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);
}
现在,您的界面应该是这样:

使用CSS和JavaScript实施暗模式
为了实施暗模式,您将使用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
    // 堆代码 duidaima.com
    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);
这使得您的页面可以通过点击切换容器来更改主题。

使用JavaScript增强暗模式
考虑以下两个改进,可以使您的暗模式网站被访客更易于使用。

检测用户偏好
这需要在网站加载之前检查用户的系统主题,并调整您的网站进行匹配。下面介绍如何使用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");
  }
拥抱以用户为中心的设计
暗模式不仅限于外观,而是把用户的舒适和偏好放在第一位。如果遵循这种方法,您可以创建对用户友好的界面,鼓励访客重复访问。您在编程和设计时,应优先考虑用户便利,并为访客提供更好的数字体验。
用户评论