Sass遍历数组和当前变量 [英] Sass Loop through array and present variable

查看:62
本文介绍了Sass遍历数组和当前变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图遍历我的颜色列表以更改背景颜色.但是以下操作失败.

I am trying to loop through my color list in order to change the background color. But the following fails.

$speech-bubble-default: $colors-chalk;
$speech-bubble-blush: $colors-blush;
$speech-bubble-brick: $colors-brick;
$speech-bubble-pink: $colors-pink;
$speech-bubble-slate: $colors-slate;

$colors-list: blush brick default pink slate;

  @each $current-color in $colors-list {
    &.speech-bubble--#{$current-color} {
      background-color: $speech-bubble--#{$current-color};

      &::after {
        border-bottom-color: $speech-bubble--#{$current-color};
      }
    }
  }

'错误:未定义的变量:"$ speech-bubble-"

'Error: Undefined variable: "$speech-bubble--"

有没有办法使它循环工作?

Is there a way to get this working in loop?

推荐答案

我认为您必须更简单一些.我将创建一个列表来管理颜色.这样,您可以正确地创建变量并避免重复代码.

I think that you have to got this simpler. I would create a list to manage colors. This way you are properly creating variables and avoid repeating code.

$colors-list:(
  default: 'chalk',
  blush: 'blush',
  brick: 'brick',
  pink: 'pink',
  slate: 'slate'
);

如果您想要一种更具描述性和语义的方式来将颜色的名称与其功能分开,则可以嵌套嵌套颜色变量,如下所示:

If you want a more descriptive and semantic way to separate the name of the color to its functionality, you can do a nested list of variables of colors like this:

  $chalk: 'chalk';
  $blush: 'blush';
  $brick: 'brick';
  $pink: 'pink';
  $slate: 'slate';


$colors-list:(
  default: $chalk,
  blush: $blush,
  brick: $brick,
  pink: $pink,
  slate: $slate
);

代码中的问题是您试图通过内插#{} 变量名称插值不受SASS支持.变量以其全名调用.您还在重复颜色列表.

The problem in your code is that you are trying to reference variables by interpolation #{} and variable name interpolation is not supported by SASS. Variables are called by its whole name. You also are repeating colors lists.

为什么不呢?

@each $key,$val in $colors-list{
  .speech-bubble--#{$key} {
    background-color: #{$val};
  }
}

这篇关于Sass遍历数组和当前变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆