如何在嵌套Sass Mixin中实现第4、5个变量的可选设置?
解决Sass Mixin中@each循环的可选参数问题
要处理$fw-icons子项的第4、5个可选参数,核心是避免直接调用nth()时因列表长度不足报错。可以通过先获取每个子项的长度,再结合条件判断为缺省的参数设置默认值(比如null,具体可根据_dms-icon的参数要求调整)。
修改后的完整Mixin代码如下:
@mixin fw-dms-icons($fw-icons, $icon-color) { $total-number-of-icons: length($fw-icons); %dms-icon-default-styles { display: inline-block; overflow: hidden; text-indent: 100%; white-space: nowrap; background-repeat: no-repeat; background-color: transparent; } @each $fw-icon-item in $fw-icons { $item-length: length($fw-icon-item); // 为可选参数设置默认值,长度不足时传入null(或其他适配_dms-icon的默认值) $param4: if($item-length >= 4, nth($fw-icon-item, 4), null); $param5: if($item-length >= 5, nth($fw-icon-item, 5), null); &.#{nth($fw-icon-item, 1)} { @include _dms-icon(nth($fw-icon-item, 2), $icon-color, nth($fw-icon-item, 3), $param4, $param5, $total-number-of-icons); @extend %dms-icon-default-styles; } } }
关键说明:
- 先通过
length($fw-icon-item)获取当前子项的参数数量,避免直接调用nth()超出列表长度导致编译错误。 - 使用
if()函数判断:当子项长度≥4时取第4个值,否则传入null(如果_dms-icon对可选参数有特定默认值,比如false或某个数值,替换成对应值即可)。 - 第5个参数的处理逻辑和第4个完全一致,确保即使只传入前3个必填参数,Mixin也能正常编译运行。
内容的提问来源于stack exchange,提问作者Keith
相关产品推荐
相关产品推荐

