im目前正在为我的网站使用暗模式,JS运行良好,它将data-theme="dark"
参数添加到html标记中,并将其存储在本地存储中。但是SCSS中的变量就是无法加载。这是我的代码:
$colorMain: #9C27B0;
$colorDisabled: rgb(92, 92, 92);
$colorTextWhite: #FFF;
$colorTextBlack: #000;
$colorTextTitle: #2b2b2b;
$colorTextPara: #4e4e4e;
$colorBgMain: #FFF;
$colorBgSec: darken($colorBgMain, 3%);
$colorAlertSuccess: #8BC34A;
$colorAlertDanger: #F44336;
$colorDarkMode: #272727;
[data-theme="dark"] {
$colorMain: rgb(176, 39, 39);
$colorDisabled: rgb(92, 92, 92);
$colorTextWhite: #FFF;
$colorTextBlack: #000;
$colorTextTitle: #2b2b2b;
$colorTextPara: #4e4e4e;
$colorBgMain: rgb(0, 0, 0);
$colorBgSec: darken($colorBgMain, 3%);
$colorAlertSuccess: #8BC34A;
$colorAlertDanger: #F44336;
$colorDarkMode: #ffffff;
}
JS:
const toggleSwitch = document.querySelector('input[name="mode"]');
function switchTheme(e) {
if (e.target.checked) {
trans()
document.documentElement.setAttribute('data-theme', 'dark');
localStorage.setItem('theme', 'dark'); //add this
} else {
trans()
document.documentElement.setAttribute('data-theme', 'light');
localStorage.setItem('theme', 'light'); //add this
}
}
toggleSwitch.addEventListener('change', switchTheme, false);
const currentTheme = localStorage.getItem('theme') ? localStorage.getItem('theme') : null;
if (currentTheme) {
document.documentElement.setAttribute('data-theme', currentTheme);
if (currentTheme === 'dark') {
toggleSwitch.checked = true;
}
}
let trans = () => {
document.documentElement.classList.add('transition');
window.setTimeout(() => {
document.documentElement.classList.remove('transition');
}, 1000)
}
有人能帮我吗D
变量不能直接加载,必须使用一些预处理lib来转换它们。或者,如果css变量适合您的用例,我建议您使用它。
看看本文的第二个实现。我已经测试了代码,它应该对你有效。干杯:(
首先,根据数据主题定义变量:
:root[data-theme="light"] {
--general-bg-color: #fff
}
:root[data-theme="dark"] {
--general-bg-color: #333
}
然后,使用独立于数据主题的颜色:
.someClass {
background-color: var(--general-bg-color)
}