在 Sass 中动态创建或引用变量 [英] Creating or referencing variables dynamically in Sass

查看:40
本文介绍了在 Sass 中动态创建或引用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use string interpolation on my variable to reference another variable:

// 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');

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

But when I do this, I get the following error:

未定义变量:$foo-".

Undefined variable: "$foo-".

Sass 是否支持 PHP 风格的变量变量?

Does Sass support PHP-style variable variables?

推荐答案

Sass 不允许动态创建或访问变量.但是,您可以将列表用于类似行为.

Sass does not allow variables to be created or accessed dynamically. However, you can use lists for similar behavior.

scss:

$list: 20px 30px 40px;    
@mixin get-from-list($index) {
  width: nth($list, $index);
}

$item-number: 2;
#smth {
  @include get-from-list($item-number);
}

生成的css:

#smth {
  width: 30px; 
}

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