在 SCSS 中动态调用变量 [英] Calling variables dynamically in SCSS

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

问题描述

我的网站有一系列已编号的颜色变量:

I have a series of color variables for my site that are numbered off:

$red-1: #821B0D;
$red-2: #B13631;
$red-3: #D75B5B;
$red-4: #F18788;
$red-5: #FDB9B0;

我想设置一个动态调用它们的 mixin,如下所示:

I'd like to set up a mixin that calls them dynamically, like this:

@mixin link($color-name) {
    color: $#{$color-name}-2;
    &:hover {
        color: white;
        background-color: $#{$color-name}-4;
    }
}

但是,我不知道如何以这种方式调用变量.(上述语法不起作用.)

However, I can't figure how to call variables in a manner like this. (The above syntax doesn't work.)

(为了避免明显的建议:我没有使用 SASS 的颜色函数,因为我的颜色不是由线性饱和度或亮度变化设置的.我无法在 SASS 中以编程方式生成它们.红色之间的亮度变化step 与 blues 之间的 step 不同,这与 greens 等的 step 不同.)

(To head off the obvious suggestion: I'm not using SASS' color functions because my colors aren't set by linear saturation or lightness variations. I can't generate them programmatically in SASS. The lightness shift in reds between steps is not the same as the one between blues, which isn't the same as the one for greens, etc.)

推荐答案

首先,您建议的语法不起作用的原因是当属性值中包含插值时,其周围的文本(例如$"符号)被解释为纯 CSS.这在关于插值的SASS参考中有所说明.

First off, the reason your suggested syntax doesn't work is because when interpolations are included in property values, the text around it (such as the '$' symbol) is interpreted as plain CSS. This is noted in the SASS reference on interpolations.

我建议改用 SASS 列表.像这样的东西会给你你想要的功能:

I'd suggest using SASS lists instead. Something like this would give you the functionality you're after:

@mixin link($color) {
    color: nth($color, 2);
    &:hover {
        color: white;
        background-color: nth($color, 4);
    }
}

$red: (#821B0D, #B13631, #D75B5B, #F18788, #FDB9B0);

.test {
    @include link($red);
}

(注意传递给 nth() 函数是从一开始的,而不是从零开始的.)

(Note that the index values passed to the nth() function are one-based, not zero-based.)

这篇关于在 SCSS 中动态调用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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