使用 Tailwind CSS 实现无闪烁的暗黑模式切换

Preview of dark mode toggle implementation

Dark layouts have become increasingly popular in interface designs, and we at Cruip are proud to have embraced this trend from the beginning. We’ve developed several best-seller Tailwind CSS templates in dark skin, and in this tutorial, we will show you how to add a dark functionality to your layout bypassing one of the most common mistakes developers make: The flickering effect.

暗色布局在界面设计中越来越受欢迎,我们在Cruip非常自豪地从一开始就拥抱了这一趋势。我们开发了几个畅销的Tailwind CSS模板,其中包含了暗色主题,并在本教程中,我们将向您展示如何为您的布局添加暗黑功能,避免开发人员常犯的一个最常见的错误:闪烁效果。

The flickering effect occurs when a user sets their preference to dark mode and navigates the site. The page initially loads in light mode but quickly switches to dark mode. This annoyance can be avoided through appropriate implementation.

闪烁效果是指当用户将偏好设置为暗黑模式并浏览网站时出现的情况。页面最初以亮色模式加载,但很快切换到暗黑模式。通过适当的实现,可以避免这种烦恼。

Let’s see how we can add a dark layout toggle to our interfaces using HTML, React, and Vue.

让我们看看如何使用HTMLReactVue为界面添加暗色布局切换。

Dark Mode implementation with HTML and JS only

仅使用 HTML 和 JS 实现深色模式

In this first part, I’ll show you how to integrate a Tailwind CSS dark mode toggle into a static website using only HTML and JavaScript.

在本文的第一部分中,我将向您展示如何仅使用HTML和JavaScript将Tailwind CSS暗黑模式切换集成到静态网站中。

Here are the steps we’ll follow:

以下是我们将要执行的步骤:

  • Enable Dark Mode in the Tailwind CSS configuration file
  • 在Tailwind CSS配置文件中启用暗黑模式
  • Create an accessible toggle button using a checkbox
  • 使用复选框创建一个可访问的切换按钮
  • Determine the default theme based on the user’s operating system preferences (prefers-color-scheme)
  • 根据用户的操作系统偏好(prefers-color-scheme)确定默认主题
  • Save the user’s preference in localStorage to remember their choice during navigation or subsequent visits
  • 将用户的偏好保存在localStorage中,以便在导航或后续访问中记住他们的选择
  • Prevent the annoying flickering effect during page loading, also known as FOUC (flash of unstyled content)
  • 防止页面加载时出现令人讨厌的闪烁效果,也称为FOUC(未样式化内容的闪烁)

Let’s get started!

让我们开始吧!

Enabling Dark Mode in Tailwind CSS

在Tailwind CSS中启用暗黑模式

If you’re familiar with Tailwind CSS, you ...

开通本站会员,查看完整译文。

首页 - Wiki
Copyright © 2011-2024 iteam. Current version is 2.137.1. UTC+08:00, 2024-11-22 06:20
浙ICP备14020137号-1 $访客地图$