[英]SCSS data-theme="dark" variables doesnt load
我目前正在為我的網站使用暗模式並且 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;
}
記者:
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
變量不能只是加載,你必須使用一些預處理庫來轉換它們。 或者,如果適合您的用例,我建議您使用 css 變量。
看這篇文章的第二個實現。 我已經測試了代碼,它應該適合你。 干杯:)
首先,根據數據主題定義變量:
:root[data-theme="light"] {
--general-bg-color: #fff
}
:root[data-theme="dark"] {
--general-bg-color: #333
}
然后,獨立於數據主題使用 colors:
.someClass {
background-color: var(--general-bg-color)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.