简体   繁体   English

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

[英]SCSS data-theme="dark" variables doesnt load

im currently working on a dark mode for my site and the JS is working fine, it adds the data-theme="dark" parameter to the html tag and stores it in the local storage.我目前正在为我的网站使用暗模式并且 JS 工作正常,它将data-theme="dark"参数添加到 html 标签并将其存储在本地存储中。 But the variables in SCSS just wont load.但是 SCSS 中的变量不会加载。 Here is my code:这是我的代码:

$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)
}

Can somebody help me?有人可以帮我吗? :D :D

The variables can't just load, you have to use some preprocessing lib to convert them.变量不能只是加载,你必须使用一些预处理库来转换它们。 Alternatively I'd recommend you to use css variables if it fits your use case.或者,如果适合您的用例,我建议您使用 css 变量。

Look second implementation of this article .看这篇文章的第二个实现。 I've tested the code, it should work for you.我已经测试了代码,它应该适合你。 Cheers :)干杯:)

First, define your variables based on the data themes:首先,根据数据主题定义变量:

:root[data-theme="light"] {
  --general-bg-color: #fff
}
:root[data-theme="dark"] {
  --general-bg-color: #333
}

Then, use the colors independently of the data theme:然后,独立于数据主题使用 colors:

.someClass {
   background-color: var(--general-bg-color)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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