0

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

4

1 回答 1

0

变量不能只是加载,你必须使用一些预处理库来转换它们。或者,如果它适合您的用例,我建议您使用 css 变量。

看这篇文章的第二个实现。我已经测试了代码,它应该适合你。干杯:)

于 2020-03-07T18:07:06.750 回答