浅色还是深色?一键切换主题以实现网站无障碍
网站和应用程序现在通常有两个不同的主题:浅色主题可在白天提供更好的可视性,深色主题可减少夜间眼睛疲劳。为了提供最佳体验,您的网站应该允许用户根据自己的喜好在这些主题之间轻松切换。本文将指导您使用 HTML、CSS 和 JavaScript 为您的网站创建深色模式切换,使用户只需单击一下即可在浅色和深色主题之间切换。
在本教程中,我们将构建一个太阳和月亮切换按钮来代表明暗模式。当用户单击该按钮时,网站将在这两种模式之间平滑过渡。我们还将用户的主题偏好保存在本地存储中以供将来访问。
查看演示或此 GitHub 存储库上的完整源代码。您可以通过此分步指南进行交互式学习,或向下滚动查看详细教程。
在我们开始之前,请确保您已经:
首先,我们将创建基本的 HTML 结构并添加必要的元素来构建我们的切换按钮和页面内容。
1。创建一个新的 HTML 文件。 打开文本编辑器并创建一个新的index.html 文件,其中包含基本的 HTML 结构,包括 DOCTYPE、HTML、head 和 body 标签。 为页面添加标题标签并导入外部 style.css 和 script.js 文件.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Light/Dark Mode Toggle</title> <link rel="stylesheet" href="style.css"> </head> <body> <script src="script.js"></script> </body> </html>
2。在正文中添加必要的元素。 在正文标记内,我们将添加以下元素:
<body> <div class="container"> <h1>Light/Dark Mode Toggle</h1> <p>Click the toggle below to switch between dark and light modes.</p> <div class="toggle-container" id="themeToggle"> <svg class="sun-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <circle cx="12" cy="12" r="5"></circle> <line x1="12" y1="1" x2="12" y2="3"></line> <line x1="12" y1="21" x2="12" y2="23"></line> <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line> <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line> <line x1="1" y1="12" x2="3" y2="12"></line> <line x1="21" y1="12" x2="23" y2="12"></line> <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line> <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line> </svg> <svg class="moon-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path> </svg> </div> </div> <script src="script.js"></script> </body>
这就是我们的普通 index.html 文件的样子:
在本节中,我们将设置 HTML 元素的样式并创建浅色和深色模式。我们还将使用过渡来实现平滑的颜色变化,并根据当前模式控制太阳和月亮图标的可见性。
3。定义浅色和深色的 CSS 变量。 在文本编辑器中打开 style.css 文件。我们将使用 :root 选择器定义深色和浅色的 CSS 变量。这允许稍后轻松定制主题。如果你想改变深色或浅色,只需要在一处更新即可。
/* Root selector for defining global CSS variables */ :root { --clr-dark: #333; /* Dark color for text in light mode, background in dark mode */ --clr-light: #fff; /* Light color for background in light mode, text in dark mode */ }
4。设置基本 CSS 样式。 为 body、.container 和 h1 元素添加样式以建立页面的布局和排版。您可以按照自己喜欢的方式自定义这些元素。
/* Base styles for the body */ body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background-color: var(--clr-light); color: var(--clr-dark); transition: background-color 0.3s, color 0.3s; } /* Container for centering content */ .container { text-align: center; } /* Heading styles */ h1 { margin-bottom: 20px; }
5。为深色模式添加 CSS 样式。 创建一个名为 .dark-mode 的 CSS 类,该类在应用于元素时交换背景和文本颜色。
/* Styles for dark mode */ .dark-mode { background-color: var(--clr-dark); color: var(--clr-light); }
6。设置切换图标的样式。 为太阳和月亮 SVG 图标添加样式,并根据当前模式控制其可见性。
/* Styles for the toggle container */ .toggle-container { cursor: pointer; } /* Styles for the sun and moon icons */ .sun-icon, .moon-icon { width: 24px; height: 24px; transition: opacity 0.3s; } /* Hide moon icon by default (light mode) */ .moon-icon { display: none; } /* Show moon icon and hide sun icon in dark mode */ .dark-mode .sun-icon { display: none; } .dark-mode .moon-icon { display: inline-block; }
使用这些 CSS 样式,您的页面将具有默认的浅色主题。光标:指针属性清楚地表明切换是可点击的。
现在我们已经有了 HTML 结构和 CSS 样式,是时候使用 JavaScript 为我们的暗模式切换添加交互性并实现本地存储来记住用户的偏好了。
7。选择 DOM 元素。 打开 script.js 文件并选择我们要修改的 DOM 元素,即 themeToggle ID,其中包含我们的切换按钮。
const themeToggle = document.getElementById('themeToggle'); const body = document.body;
8. Add event listeners to the toggle button. This is the core functionality of the dark mode toggle. Add an event listener to the themeToggle element to detect when the user clicks on it. It will add the dark-mode class to the body element if it’s absent, or removes the class if present.
themeToggle.addEventListener('click', () => { body.classList.toggle('dark-mode'); });
At this point, the toggle switch is functional, and clicking on it will switch between light and dark modes. However, if you reload the page while in dark mode, the website will revert to its default light mode.
9. Save user theme preferences in local storage. To save the user's theme preference even after the browser is closed, we'll use the localStorage object. Inside the event listener callback function, it checks if the body element has the dark-mode class.
themeToggle.addEventListener('click', () => { body.classList.toggle('dark-mode'); // Store user preference in local storage if (body.classList.contains('dark-mode')) { localStorage.setItem('theme', 'dark-mode'); } else { localStorage.setItem('theme', ''); } });
10. Check for a saved theme preference. When the page loads, we want to check if there's a saved theme preference in the local storage. Use localStorage.getItem() to retrieve the value associated with the 'theme' key. If a 'dark-mode' preference exists in the local storage, apply the dark mode theme immediately by adding the dark-mode class to the body element.
Note: Make sure to place the getItem() method before the event listener to ensure it runs on page load.
// Check if user preference exists in local storage const currentTheme = localStorage.getItem('theme'); if (currentTheme) { body.classList.add(currentTheme); }
We've implemented all the necessary components for our dark mode toggle, so let's see it in action. Try clicking the toggle switch to see the smooth transition between light and dark themes. Refresh the page to verify your theme preference is remembered.
Check out the complete source code on this GitHub repository.
Creating a dark mode toggle is just the beginning. To create a user-friendly dark mode experience, there are several best practices to keep in mind.
Selecting colors for dark mode involves more than simply inverting your light theme. The goal is to create a contrast between text and background colors for readability. Use tools like color contrast checkers to verify that your chosen colors meet WCAG (Web Content Accessibility Guidelines) standards. Remember, a well-designed dark mode should be easy on the eyes and work well across devices.
Create a clear visual distinction between light and dark modes to help users identify each mode easily. Your toggle switch or button should clearly show the current mode. You can implement effective approaches such as a sun and moon icon toggle, which is used in this article and is an easily recognizable choice, a light and dark mode text button, or a sliding switch with light/dark mode labels. Whichever design you choose, make sure it's consistent with your user interface and provides clear feedback when the user interacts with it.
To create a more polished user experience, use CSS transitions or animations for a seamless shift between light and dark modes. Make sure that all elements, including images and icons, smoothly transition to the new color scheme. This can be done by adjusting opacity, brightness, or swapping out images for dark mode-specific versions.
Adding a dark mode toggle to your website greatly improves user experience. This is not just about aesthetics but also usability and accessibility. It allows users to view content comfortably based on their preferences and lighting conditions.
Throughout this article, we've walked through the process of creating a simple dark mode toggle, covering HTML structure, CSS styling for light and dark themes, JavaScript functionality, and storing user preference. The key is to keep it simple and user-friendly. Don't forget to test your dark mode thoroughly to ensure all elements remain readable and functional.
Now it's your turn to create your own dark mode toggle! Share your CodePen or GitHub link in the comments below.
Check out these resources to learn more about dark mode implementation and advanced techniques:
以上是如何使用 HTML、CSS 和 JavaScript 创建深色模式切换的详细内容。更多信息请关注PHP中文网其他相关文章!