我有一个生成CSS文件的Sass文件.我在我的sass文件中使用了很多变量来获取背景颜色,字体大小,现在我想通过JavaScript控制我的所有变量.
例如,在style.sass中我们有
$bg : #000;
$font-size: 12px;
Run Code Online (Sandbox Code Playgroud)
如何从JavaScript更改这些值?
GJK*_*GJK 15
你不能.SASS是一个CSS预处理器,这意味着当您将其编译为CSS时,所有 SASS特定信息都会消失.
Kru*_*ull 14
CSS
:root {
subTitleLeftMargin: 1.5vw;
}
.element {
margin-left: var(--subTitleLeftMargin);
}
Run Code Online (Sandbox Code Playgroud)
JS 或 TS
document.documentElement.style.setProperty("--subTitleLeftMargin", "6vw");
Run Code Online (Sandbox Code Playgroud)
使用 Sass 或任何其他变量来设置初始值
JavaScript 设置同名的 CSS 自定义属性,以根据需要更新这些值(同名只是一种偏好)。
您不需要定义 CSS 根属性,因为 Sass 变量是后备变量并且将首先使用。这允许您使用 Sass 或任何其他样式处理器在服务器端执行任何您想要的操作,并更新客户端的值。
这是控制背景颜色的颜色选择器的示例。
CSS
$selectedColor: #000;
body {
background: var(--selectedColor, $selectedColor);
}
Run Code Online (Sandbox Code Playgroud)
html
<input type="color">
Run Code Online (Sandbox Code Playgroud)
js
const colorInput = document.querySelector('[type=color]')
// Set the CSS custom property --selectedColor on the root element
// Now JavaScript controls this variable and everywhere you used Sass variables if you follow this pattern
const handleColorInput = e => document.documentElement.style.setProperty("--selectedColor", e.target.value)
colorInput.addEventListener('input', handleColorInput)
Run Code Online (Sandbox Code Playgroud)
我还需要此功能,这对我有用:
使用JS,您可以将类设置为body,例如。.blue或.default
现在,创建一组要从其扩展的规则:
.default .themeColor {
color: 'red';
}
.blue .themeColor {
color: 'blue';
}
Run Code Online (Sandbox Code Playgroud)
现在,不要color: $someColor像这样在您的scss文件中使用它:
.someClass {
@extend .themeColor;
}
Run Code Online (Sandbox Code Playgroud)
现在,如果您的身体有该default类别,则内部颜色someClass将为红色,而如果身体将有该blue类别,则颜色将为蓝色。