【问题标题】:Use a particular Sass map depending on variable根据变量使用特定的 Sass 映射
【发布时间】:2018-07-16 11:56:03
【问题描述】:

我遇到了一个问题,我可以更轻松地定义两个可以在使用单个变量之间切换的基本地图(对于基本、浅色/深色主题来说似乎更容易)

https://codepen.io/anon/pen/bLwNaW

我正在尝试设置 $theme-being-used,在 If/Else 中检查它并根据该结果使用特定地图。 这让我很容易进入并将 $theme-being-used 设置为暗色并更改所有基本变量。

我试过了:

@if (#{$theme-being-used} == light) {

@if ($theme-being-used == light) {

@if (#{$theme-being-used} == "light") {, etc..

有人知道这是否可以做到吗?无论哪种方式都没什么大不了的,只是在抛出模板网站时节省了一点时间。

在我通过简单地注释/取消注释代码来实现这一点之前,即

$palette: (
    // Light 
    ui: (
        primary:    #FFFFFF,
        secondary:  #EEEEEE,
        alternate:  #DDDDDD
    ),
    // Dark - COMMENTED when I want to use light variables
    /*ui: (
        primary:    #333,
        secondary:  #444,
        alternate:  #555
    ),*/
);

这很好而且很快,但是将它设置在一个地方会更容易,而不必这样做。

谢谢。

【问题讨论】:

    标签: css sass sass-maps


    【解决方案1】:

    $theme-being-used 勾选到_palette 函数。这个函数只接受一个参数——颜色名称。并在其内部包含所有颜色选择逻辑。

    萨斯迈斯特demo.

    $theme-being-used: light;
    
    $palette: (
        dark: (
            primary:   red,
            secondary: orange,
            tertiary:  blue
        ),
        light: (
            primary:   green,
            secondary: black,
            tertiary:  yellow
        )
    );
    
    @function _palette($color-name, $theme-name: $theme-being-used) {
      // Select one of available themes
      // Here there may be more complex logic in choosing themes
      $theme: map-get($palette, #{$theme-name});
    
      // Get the color from theme
      @return map-get($theme, #{$color-name});
    }
    
    .s-o {
      background: _palette(primary);
    
      &:hover {
        background: _palette(secondary);
      }
    }
    

    【讨论】:

    • 嘿@3rdthemagical,非常感谢您的回复!我的设置看起来非常相似。我已经把它设置得更像我的了,我试图只在一个位置更改一个变量,并让其余的变量根据该值用特定的地图编译。 sassmeister.com/gist/2bff100a405cff68f22a7d1aba73a080 如您所见,我正在尝试将 $theme-being-used 更改为 light/其他东西,并让 IF/ELSE 决定应该使用哪个 Map。如果可以做到,那就太好了,如果没有,感谢您的帮助!
    • 你得到错误Undefined variable: "$palette". 为避免这种情况,你可以使用!global 标志或全局定义$palette var。
    • 传奇,就是这样。必须与控制指令内的地图有关吗?无论哪种方式都非常感谢!
    • 我已经使用 !global 但感谢您向我展示 null 选项,我不知道我也可以这样做。再次感谢。
    猜你喜欢
    • 2022-11-02
    • 1970-01-01
    • 2016-12-27
    • 2015-06-24
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 2017-11-24
    相关资源
    最近更新 更多