Sass \`each具有多个变量

css CSS

Tony凯

2020-03-23

我刚刚开始使用Sass和Compass,我喜欢它。我想做的就是利用该@each功能简化重复的任务。但是,我仅看到了@each插入一个变量的示例,并且我希望能够使用多个变量。

标准方式(来自Sass参考):

@each $animal in puma, sea-slug, egret, salamander {
  .#{$animal}-icon {
    background-image: url('/images/#{$animal}.png');
  }
}

很棒,但是我希望能够执行以下操作:

@each {$animal $color} in {puma black}, {sea-slug green}, {egret brown}, {salamander red} {
  .#{$animal}-icon {
    background-color: #{$color};
  }
}

这可能吗?

第2833篇《Sass \`each具有多个变量》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
前端Green 2020.03.23

如果有人需要,我使用的另一种方式:

$i:0;
@each $name in facebook, twitter, google_plus, instagram, youtube, pinterest {
    $i:$i+1;
}
小卤蛋 2020.03.23

Sass 3.3.0及更高版本支持此功能(我刚刚从3.2.14更新到3.4.4以使用它)。

@each $animal, $color in (puma, black), (sea-slug, green), (egret, brown), (salamander, red) {
  .#{$animal}-icon {
    background-color: $color;
  }
}

如果您要更新Sass,建议您检查变更日志中是否存在向后不兼容的情况。

Sass参考使用@each进行多项分配

2020.03.23

我在同一条船上(Sass / Compass的初学者),不得不做类似的事情。这是我使用嵌套列表想到的:

$flash_types: (success #d4ffd4) (error #ffd5d1);

@each $flash_def in $flash_types {
    $type: nth($flash_def, 1);
    $colour: nth($flash_def, 2);

    &.#{$type} {
        background-color: $colour;
        background-image: url(../images/#{$type}.png);
    }
}

这不是最优雅的解决方案,但是如果您找不到其他任何东西,它应该可以工作。希望能帮助到你!我也希望有更好的方法:)

2020.03.23

刚遇到这个,为您找到答案。在Sass中,实际上可以有一个多维列表,因此,您无需创建单个变量,而是创建一个变量来保存所有变量,然后遍历它们:

$zoo: puma black, sea-slug green, egret brown, salamander red;

@each $animal in $zoo {
  .#{nth($animal, 1)}-icon {
    background-color: nth($animal, 2);
  }
}

您可以拥有多维列表,就像拥有一维列表一样,只要每个嵌套维以不同的方式(在本例中为逗号和空格)分开即可。

更新2013年10月24日

在Sass 3.3中,有一个称为maps的新数据类型,它是一组散列的项目。这样,我们可以通过以下方式重写我以前的答案,使其更接近所需的结果:

$zoo: ("puma": black, "sea-slug": green, "egret": brown, "salamander": red);

@each $animal, $color in $zoo {
    .#{$animal}-icon {
        background-color: $color;
    }
}

您可以在SassMeister上看到这一点

阿飞 2020.03.23

另一种解决方案是创建不同的列表并“压缩”它们。

//Create lists
$animals: puma, sea-slug, egret, salamander;
$animals-color: black, green, brown, red;

//Zip lists
$zoo: zip($animals, $animals-color);

//Do cycle
@each $animal, $color in $zoo {
    .#{$animal}-icon {
        background-color: $color;
    }
}

维护此解决方案可能比其他解决方案更为复杂,但是如果您多次使用列表,则可以节省时间。(是我的情况)

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android