How to control Sass Variable with javascript

2020-01-29 08:32发布

I have a Sass file which is generating a CSS file. I have used many variables in my sass file for background color, font-size, now I want to control my all variables through JavaScript.

For example, in style.sass we have

$bg : #000;
$font-size: 12px;

How can I change these values from JavaScript?

7条回答
女痞
2楼-- · 2020-01-29 08:47

Share data between Sass and JavaScript using JSON.

See related question https://stackoverflow.com/a/26507880/4127132

查看更多
▲ chillily
3楼-- · 2020-01-29 08:52

I find sass-extract-loader especially helpful for using with Create-React-App.

You can use it like:

_variables.scss

$theme-colors: (
  "primary": #00695F,
  "info": #00A59B
);

component.tsx

 const style = require('sass-extract-loader!./_variables.scss');
 const brandInfo = style.global['$theme-colors'].value.primary.value.hex; // '#00695F';
查看更多
放荡不羁爱自由
4楼-- · 2020-01-29 08:54

CSS

:root {
  subTitleLeftMargin: 1.5vw;
}

.element {
  margin-left: var(--subTitleLeftMargin);
}

JS or TS

document.documentElement.style.setProperty("--subTitleLeftMargin", "6vw");
查看更多
Summer. ? 凉城
5楼-- · 2020-01-29 08:54

If you're looking to do what bootstrap do (ie editing fields to download a theme).

You'd have to:

  1. Have the files on hand that you want to edit
  2. Store these variables as a string, and use .replace() to search and replace variables
  3. Output this string and compile it to a file and or zip it up for download.

I'd personally do this with php.

查看更多
放荡不羁爱自由
6楼-- · 2020-01-29 08:56

I also needed this functionality, here's what worked for me:

With JS you can set a class to body, ex. .blue or .default Now create a set of rules to extend from, which you'd like to set:

.default .themeColor {
  color: 'red';
}
.blue .themeColor {
  color: 'blue';
}

Now instead of having color: $someColor in your scss file, use it like this:

.someClass {
   @extend .themeColor;
 }

Now, if your body will have the default class, the color inside someClass will be red, and if body will have the blue class the color will be blue.

查看更多
Root(大扎)
7楼-- · 2020-01-29 09:04

You can't. SASS is a CSS preprocessor, which means that all SASS specific information disapears when you compile it to CSS.

查看更多
登录 后发表回答