繁体   English   中英

SCSS data-theme="dark" 变量不加载

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM