【问题标题】:How to use default variable if some variable is not there for other theme in scss?如果 scss 中的其他主题没有某些变量,如何使用默认变量?
【发布时间】:2020-05-09 18:34:37
【问题描述】:

所以我正在编写一个主题为浅(默认)和深色的网络应用程序。根据这篇文章How to Create a Dark Mode in Sass,我正在使用SCSS。我可以创建明暗,也可以创建多个主题。但我必须实现这样的目标。

这是场景:

我有一个问题,在文章中提到的解决方法中,如果我没有暗版的bg: $bg--light, 并且只有默认值怎么办。像这样

$themes: (
        default: (
                logo: url("../images/brand/logo_vertical.svg"),
                bg: $bg--light,
                text: $text--light,
        ),
        dark: (
                logo: url("../images/brand/logo_vertical--invert.svg"),
                text: $text--dark,
        ),
);

@mixin themed() {
  @each $theme, $map in $themes {
    .theme--#{$theme} & {
      $theme-map: () !global;
      @each $key, $submap in $map {
        $value: map-get(map-get($themes, $theme), '#{$key}');
        $theme-map: map-merge($theme-map, ($key: $value)) !global;
      }
      @content;
      $theme-map: null !global;
    }
  }
}

@function t($key) {
  @return map-get($theme-map, $key);
}

.base {
  @include themed() {
    color: t($text);
    background: t($bg);
  }
}

这会导致在黑暗中没有bg: $bg--light, 的错误。如果 bg: $bg--light, 不存在用于黑暗或任何其他将使用默认主题的主题,我能做些什么。

这可能吗?怎么样?

如果密钥不存在,我有什么办法可以写 if condition 以使用默认值。

【问题讨论】:

    标签: css sass themes scss-mixins


    【解决方案1】:

    是的,你可以通过 if 条件得到你想要的。首先,将您的默认主题存储在一个变量中:

    $default-theme: map-get($themes, default);
    

    然后,在您的函数t 中,使用内置函数map-has-key 检查密钥是否存在,并使用结果通过ternary 运算符选择所需的主题图:

    @function t($key) {
      $key-exists: map-has-key($theme-map, $key);
      @return map-get(if($key-exists, $theme-map, $default-theme), $key);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-30
      • 2017-02-02
      • 2019-07-23
      • 1970-01-01
      • 2015-11-27
      • 2020-01-08
      • 1970-01-01
      相关资源
      最近更新 更多