我目前正在为我的网站使用暗模式,并且 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