Tailwindcss开启黑夜模式

时间:2025-03-17 19:58:38

        本篇讲述如何使用tailwindcss切换白天黑夜主题

        tailwindcss自带的暗夜切换会比css自带的theme主体切换来得方便很多,学习成本也很低,只要求会用tailiwndcss

1,tailwindcss.config有两种暗夜模式切换,媒体查询和手动类切换。手动控制需要开启类模式

// tailwind.config.js
export default {
    ...
    darkMode:'class', // 使用class策略
}

2,设置点击切换事件:点击为html根元素添加dark类

// 切换主体颜色(直接修改html的类)
const toggleTheme = () => {
    const html = document.documentElement

    html.classList.toggle('dark')
    if (html.classList.contains('dark')) {
        localStorage.setItem('Dark', 'true')
    } else {
        localStorage.removeItem('Dark')
    }
}

切换后 将是否有dark类 存放在localstorage中,保持记忆性

3,进入网页前,记忆用户选择的模式,在index.html中写入函数,使其在页面渲染前执行,如果localstorage已经存放了dark 代表开启暗夜模式 如果没有 则不执行

// index.html  
<head>
<script>
      // 在页面渲染前执行
      (function() {
        if (localStorage.getItem('Dark')) {
          document.documentElement.classList.add('dark');
        }
      })();
    </script>
</head>