译者 | 布加迪
审校 | 重楼
近年来,暗模式作为用户界面选项备受追捧。它提供了更暗的背景和更亮的文本,不仅可以减轻眼睛疲劳,还可以节省电池续航时间,尤其是在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.28at.com/showinfo-26-12700-0.html如何使用CSS和JavaScript实施暗模式?
声明:本网页内容旨在传播知识,不代表本站观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。