You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scss如何通过已有变量与字符串拼接生成新变量并取值

解决Sass Typography Mixin动态引用变量的问题

你当前的代码核心问题是:只是拼接出了变量名称的字符串,没有实际引用对应的变量值。Sass需要通过动态变量引用语法,才能识别拼接后的字符串是一个变量并获取其值。

方案1:修改现有代码实现动态变量引用

直接调整mixin中font-size、font-weight、line-height的赋值语句,使用#{}插值语法拼接变量名并引用:

$font-family-default : "Helvetica", "Arial", "sans-serif";

$body-bold-m-font-size : 34px;
$body-bold-m-font-weight: 900;
$body-bold-m-line-height: 40px;

@mixin typo($type, $weight, $size) {
  font-family: $font-family-default;
  color: green; // 测试用
  
  $constructed-typo : $type+'-'+$weight+'-'+$size;
  // 使用#{}插值拼接变量名,再通过$引用变量值
  font-size: $#{$constructed-typo}-font-size;
  font-weight: $#{$constructed-typo}-font-weight;
  line-height: $#{$constructed-typo}-line-height;
}

.electric-sheep {
  @include typo(body, bold, m);
}

编译后会输出正确的CSS:

.electric-sheep {
  font-family: "Helvetica", "Arial", "sans-serif";
  color: green;
  font-size: 34px;
  font-weight: 900;
  line-height: 40px;
}

方案2:使用Map存储排版令牌(推荐更易维护)

如果后续要扩展更多排版样式,单独变量会变得杂乱,建议用Sass Map来结构化存储所有排版规则,代码更清晰:

$font-family-default : "Helvetica", "Arial", "sans-serif";

// 用嵌套Map组织所有排版属性
$typography-map: (
  body: (
    bold: (
      m: (
        font-size: 34px,
        font-weight: 900,
        line-height: 40px
      )
    )
  )
);

@mixin typo($type, $weight, $size) {
  font-family: $font-family-default;
  color: green; // 测试用
  
  // 逐层取出对应排版属性
  $typo-properties: map-get(map-get(map-get($typography-map, $type), $weight), $size);
  
  font-size: map-get($typo-properties, font-size);
  font-weight: map-get($typo-properties, font-weight);
  line-height: map-get($typo-properties, line-height);
}

.electric-sheep {
  @include typo(body, bold, m);
}

这种方式后续新增排版样式(比如body-regular-l),只需在$typography-map中添加对应层级的属性即可,无需新增大量单独变量,维护成本更低。

内容的提问来源于stack exchange,提问作者Ciloow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 16:23:10