访问变量的名称而不是它的值 [英] Accessing the name of the variable rather than its value

查看:38
本文介绍了访问变量的名称而不是它的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个循环,循环显示颜色并压缩我的 scss 文件中的代码量.这是我所拥有的一个简单示例:

I am trying to write a loop that will cycle through colors and condense the amount of code in my scss file. Here is a simple example of what I have:

$color1: blue;
$color2: red;
$color3: white;
$color4: black;

.color1-bg { background-color: $color1; }
.color2-bg { background-color: $color2; }

.color1-border { border-color: $color1; }
.color2-border { border-color: $color2; }

等等.

我正在寻找一种编写循环的方法,以便当我使用变量生成类时,它具有变量的名称而不是其值:

I am looking for a way to write a loop so that when I use the variable to generate the class, it has the name of the variable rather than its value:

@each $color in $colour1, $colour2, $colour3, $colour4 {
    .#{$color}-bg { background-color: $color; }
    .#{$color}-border { border-color: $color; }
}

推荐答案

您不能直接访问变量的名称,您必须将其存储为附加值.

You can't access the name of the variable directly, you'd have to store it as an additional value.

Sass 还没有映射,所以下一个最好的方法是列表列表.

Sass doesn't have mappings yet, so the next best thing is a list of lists.

$color1: ('color1', blue);
$color2: ('color2', red);
$color3: ('color3', white);
$color4: ('color4', black);

@each $color in $color1, $color2, $color3, $color4 {
    $name: nth($color, 1);
    $value: nth($color, 2);
    .#{$name}-bg { background-color: $value; }
    .#{$name}-border { border-color: $value; }
}

Sass 3.3 及更新版本(映射)

从 3.3 开始,您可以访问映射.它在功能上与列表列表相同,但在语法上更简洁.

Sass 3.3 and newer (mappings)

Starting with 3.3, you have access to mappings. It's functionally the same as the list of lists, but syntactically more concise.

$colors:
    ( 'color1': blue
    , 'color2': red
    , 'color3': white
    , 'color4': black
    );

@each $name, $value in $colors {
    .#{$name}-bg { background-color: $value; }
    .#{$name}-border { border-color: $value; }
}

交替

或者,如果您的颜色名称确实是color1"、color2"等,您也可以直接构建名称而不是明确指定它们:

Alternately

Or if your color names are really "color1", "color2", etc., you can also just construct the name on the fly rather than specifying them explicitly:

$color1: blue;
$color2: red;
$color3: white;
$color4: black;

$num: 0;
@each $color in ($color1, $color2, $color3, $color4) {
    $num: $num + 1;
    .color#{$num}-bg { background-color: $color; }
    .color#{$num}-border { border-color: $color; }
}

这篇关于访问变量的名称而不是它的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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