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

Sass for循环中动态参数调用自定义color函数无法取色问题

问题根因

你的$shade-colors映射表的键是数字类型,而循环中使用#{$i}00插值生成的是字符串类型的"100"、"200"等值。Sass的map-get方法会严格匹配键的类型,数字和字符串即使字面量相同也会被判定为不同的键,因此无法查询到对应颜色值。

修复方案

方案1(推荐):循环中直接生成数字类型的键

不用插值生成键,直接通过数值计算得到数字类型的 shade 键传入函数即可:

@for $i from 1 through 9 {
    $shade-key: $i * 100;
    $val: color('shade', $shade-key);
    --color-shade-#{$shade-key}: #{$val};
}

方案2:修改color函数兼容字符串类型键

如果不想修改循环逻辑,可以在shade分支先把传入的参数转为数字再查询:

@function color($cat, $color, $shade: base) {
    @if ($cat == 'theme') {
        @return map-get($theme-colors, $color, $shade);
    }
    @else if ($cat == 'shade') {
        $color: if(type-of($color) == string, $color + 0, $color);
        @return map-get($shade-colors, $color);
    }
    @else {
        @return map-get($cat, $color, $shade);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:27:03