主题管理
在现代网站中,我们已经看到它具有深色和浅色主题的功能,这对用户产生了良好的影响。他们可以根据自己的喜好更改主题。
为了实现这一点,我们还在使用 tailwindcss 进行样式设置。
首先,我们必须在我们的网站中安装 tailwindcss。在 Qwik 项目中添加 tailwind 非常简单。您只需在终端中运行以下命令。
npm run qwik add tailwind
您必须从您的 tailwind.config.js
文件中启用深色模式。它应该看起来像这样。
module.exports = {
content: ["./src/**/*.{js,ts,jsx,tsx,mdx}"],
darkMode: "class",
theme: {},
plugins: [],
};
然后,我们必须将此代码添加到我们 root.tsx
文件的 head 标签中。
<script
dangerouslySetInnerHTML={`
(function() {
function setTheme(theme) {
document.documentElement.className = theme;
localStorage.setItem('theme', theme);
}
var theme = localStorage.getItem('theme');
console.log(theme);
if (theme) {
setTheme(theme);
} else {
setTheme('light');
}
})();
window.addEventListener('load', function() {
var themeSwitch = document.getElementById('hide-checkbox');
themeSwitch.checked = localStorage.getItem('theme') === 'light'? true: false;
}
);
`}
></script>
您可以将变量名“hide-checkbox”更改为您想要的任何名称。它需要与我们在 html 文件中的一样。
然后,您可以在任何组件中添加您的主题切换代码。
import { component$, useStylesScoped$ } from "@builder.io/qwik";
import styles from "./style.css?inline";
export const ThemeSwitch = component$(() => {
useStylesScoped$(styles);
return (
<div class="flex items-center gap-3">
<label class="switch">
<input
type="checkbox"
id="hide-checkbox"
onClick$={() => {
const theme = document.documentElement.className;
if (theme === "light") {
document.documentElement.className = "dark";
localStorage.setItem("theme", "dark");
} else {
document.documentElement.className = "light";
localStorage.setItem("theme", "light");
}
}}
/>
<span class="slider round"></span>
</label>
</div>
);
});
用于主题切换的样式。
.switch{
position: relative;
display: inline-block;
width: 50px;
height: 30px;
background-color: red;
border-radius: 100px;
cursor: pointer;
}
.switch input{
display: none;
}
.slider{
width: 50px;
height: 25px;
border-radius: 25px;
background-color: #ccc;
position: relative;
cursor: pointer;
transition: all .3s linear;
}
.slider:before{
content: "";
position: absolute;
width: 25px;
height: 25px;
background-size: cover;
border-radius: 50%;
background-color: #fff;
top: 15px;
left: 5px;
bottom: 0;
margin: auto;
transition: all .3s linear;
}
input:checked + .slider{
background-color: #2196F3;
}
input:checked + .slider:before{
left: 22px;
}
然后运行代码。您将拥有深色和浅色主题的功能。