【问题标题】:Change all variable value based on body class根据身体类别更改所有变量值
【发布时间】:2017-09-15 04:42:49
【问题描述】:

我正在研究基于主题的本地化。为此,我正在为每个本地化获取关于 body 标签的课程。 我需要根据该类更改所有变量值 了解更多

$a: #000;
$b= Arial;

if body has class Australia then
$a: #ff0000;
$b: 'Roboto';

请不要只使用scss的js代码

【问题讨论】:

  • 与一小时前提出的这个问题几乎相同? stackoverflow.com/questions/42249085/…
  • 我检查了那个问题,但没有帮助。它提到了一组元素。但对我来说,整个网站都需要它。这些变量在多个类中多次使用。

标签: css sass


【解决方案1】:

使用 @import 和 !default 变量

// –––––––––––––––––––––––––––––––––––––– 
// _style.scss 
// underscore added to prevent compilation 
// ––––––––––––––––––––––––––––––––––––––

$color      : red   !default;
$font-family: Arial !default; 

.foo { color: $color; }
.bar { font-family: $font-family; }



// ––––––––––––––––––––––––––––––––––––––
// style.scss (compile file) 
// ––––––––––––––––––––––––––––––––––––––
// redefine variables
$color: blue;
$font-family: Roboto;

// add wrapper if needed (will be added to all selectors)
.australia {
    @import '_style.scss';
}

【讨论】:

    【解决方案2】:

    以下示例使用地图来定义不同的主题值。 mixin 会将每个选择器包装在一个类(映射键)中,并创建要在每个选择器内部使用的全局变量。

    $theme-map:(
      '.australia': (color: blue, font-family: Roboto),
      '.denmark'  : (color: red,  font-family: Arial)    
    );
    
    
    @mixin theme {
      @each $class, $map in $theme-map {
        #{$class} & { 
          $color:       map-get($map, color)       !global;
          $font-family: map-get($map, font-family) !global;
          @content;
        }
      }
    }
    
    
    
    .foo {
      @include theme {
        color: $color;
        font-family: $font-family;
      }
    }
    
    
    .bar{
      @include theme {
        background-color: $color;
      }
    }
    

    输出:

    .australia .foo {
      color: blue;
      font-family: Roboto;
    }
    .denmark .foo {
      color: red;
      font-family: Arial;
    }
    
    .australia .bar {
      background-color: blue;
    }
    .denmark .bar {
      background-color: red;
    }
    

    PS。在不久的将来,CSS 变量将使用变量继承来简化这类工作。

    .australia {
       --color: red;
       --font-family : Arial;
    }
    
    .denmark {
       --color: blue;
       --font-family : Roboto;
    }
    
    
    
    .foo {
       color: var(--color);
       font-family: var(--font-family);
    }
    
    .bar {
       backgound-color: var(--color);
    }
    

    【讨论】:

    • 我不想编辑每个选择器。因为有成千上万的选择器使用这些变量。编辑每一个都需要一生..
    • 在这种情况下,可以使用 @import 和 !default 变量——我将添加一个新示例。另请注意有关 CSS 变量的更新部分
    猜你喜欢
    • 2018-06-30
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 2011-10-29
    • 2020-01-02
    • 1970-01-01
    • 2016-11-01
    • 1970-01-01
    相关资源
    最近更新 更多