How to control Sass Variable with javascript

前端 未结 8 1598
予麋鹿
予麋鹿 2020-12-01 17:47

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

相关标签:
8条回答
  • 2020-12-01 18:31

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

    0 讨论(0)
  • 2020-12-01 18:34

    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.

    0 讨论(0)
  • 2020-12-01 18:35

    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';
    
    0 讨论(0)
  • 2020-12-01 18:35

    variable in style

    :root {
    
      --bg: #000;
      --font-size:12px;
    
    }
    

    change variable value by javascript

    root.style.setProperty('--bg', '#fff');
    root.style.setProperty('--font-size', '14px');
    
    0 讨论(0)
  • 2020-12-01 18:36

    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.

    0 讨论(0)
  • Share data between Sass and JavaScript using JSON.

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

    0 讨论(0)
提交回复
热议问题