主体类更改时如何更改sass导入文件 [英] How to change sass import file when body class is changing
问题描述
当主体中的类发生变化时,是否可以通过颜色变量来更改scss文件?
Is any way to change scss file with color variables when class in body is changing?
我的意思是当我使用html时:
I mean when I have in html:
<body class="custom"> ... </body>
我要加载style.scss
I want to load in style.scss
@import 'custom';
还有我的时候
<body class="dark-mode"> ... </body>
我要加载style.scss
I want to load in style.scss
@import 'dark-mode';
推荐答案
您不能根据条件创建 @import
,但是还有很多其他方法可以实现.这是我当时写的一个小框架.
You can not make an @import
depending on a condition, but there is a ton of possible other approaches to this. Here is a small framework I wrote back then.
@function keyFilter($iKey, $fKey, $rKey) {
@if ($iKey == $fKey) {
@return $rKey;
}
@return $iKey;
}
@function v($key) {
@return var(--#{$key});
}
//
$modes: (
"&": (
"color": #000,
),
"dark": (
"color": #fff,
),
);
//
@each $key, $map in $modes {
body#{keyFilter("[#{$key}]", "[&]", null)} {
@each $key, $value in $map {
--#{$key}: #{$value};
}
}
}
要注册"一个新的模式只需在 $ modes
-map中嵌套另一个地图,您就可以根据需要添加任意多个模式.请记住,&"
-mode表示默认模式.
To "register" a new mode just nest another map in the $modes
-map, you can add as many modes as you want. Keep in mind the "&"
-mode represents the default-mode.
$modes: (
"&": (
//...
),
"dark": (
//...
),
//...
);
要注册依赖于模式的新变量,只需输入相应模式的键和值即可.
To register a new mode-depending variable just simply enter key and value to the respective mode.
$modes: (
"&": (
"color": #000,
"bgc": #fff,
"bgc-contrast": #eee,
//...
),
"dark": (
"color": #fff,
"bgc": #000,
"bgc-contrast": #424242,
//...
),
);
要调用变量,只需使用 v($ key)
函数.
To call a variable just use the v($key)
function.
body {
color: v(color);
background-color: v(bgc);
}
div.contrasted {
background-color: v(bgc-contrast);
}
此编译为:
body {
--color: #000;
--bgc: #fff;
--bgc-contrast: #eee;
}
body[dark] {
--color: #fff;
--bgc: #000;
--bgc-contrast: #424242;
}
body {
color: var(--color);
background-color: var(--bgc);
}
div.contrasted {
background-color: var(--bgc-contrast);
}
注意:您无需为每种模式声明每个变量.如果找不到当前模式的变量,则不会抛出错误.
例如:This ...
Note: you do not need to declare each variable for each mode. If a variable wasn't found for the current mode, this won't throw an error.
For Example: This...
$modes: (
"&": (
//...
),
"dark": (
"color": #fff,
"bgc": #000,
"bgc-contrast": #424242,
//...
),
);
//...
body {
color: v(color);
background-color: v(bgc);
}
div.contrasted {
background-color: v(bgc-contrast);
}
...很好.
这篇关于主体类更改时如何更改sass导入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!