在Sass中动态创建或引用变量

在Sass中动态创建或引用变量

我试图在变量上使用字符串插值来引用另一个变量:

// Set up variable and mixin$foo-baz: 20px;@mixin do-this($bar) {
    width: $foo-#{$bar};}// Use mixin by passing 'baz' string as a param for use $foo-baz variable in the mixin@include do-this('baz');

但是,当我这样做时,我会得到以下错误:

未定义变量:“$foo-”。

Sass支持PHP风格的变量吗?


郎朗坤
浏览 3217回答 3
3回答

繁星coding

这实际上可以使用Sass映射而不是变量。下面是一个简单的例子:动态引用:$colors: (   blue: #007dc6,   blue-hover: #3da1e0 ); @mixin colorSet($colorName) {     color: map-get($colors, $colorName);     &:hover {         color: map-get($colors, $colorName#{-hover});     } } a {     @include colorSet(blue); }产出如下:a { color:#007dc6 } a:hover { color:#3da1e0 }动态创建:@function addColorSet($colorName, $colorValue, $colorHoverValue: null) {   $colorHoverValue: if($colorHoverValue == null, darken( $colorValue, 10% ), $colorHoverValue);   $colors: map-merge($colors, (     $colorName: $colorValue,     $colorName#{-hover}: $colorHoverValue   ));   @return $colors; } @each $color in blue, red {   @if not map-has-key($colors, $color) {     $colors: addColorSet($color, $color);   }   a {     &.#{$color} { @include colorSet($color); }   } }产出如下:a.blue { color: #007dc6; } a.blue:hover { color: #3da1e0; } a.red { color: red; } a.red:hover { color: #cc0000; }

千万里不及你

每当我需要使用条件值时,我都依赖于函数。下面是一个简单的例子。$foo: 2em; $bar: 1.5em; @function foo-or-bar($value) {   @if $value == "foo" {     @return $foo;   }   @else {     @return $bar;   } } @mixin do-this($thing) {   width: foo-or-bar($thing); }
打开App,查看更多内容
随时随地看视频慕课网APP