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

SASS使用@each循环生成类名时如何将空格替换为'-'

解决方案

核心逻辑是仅在生成类名时做空格转连字符的处理,CSS属性值保持原始参数不变,完全不会和text-decoration的属性规则冲突。

适用Dart Sass 1.50.0+版本(当前主流Sass版本)

直接使用Sass内置的str-replace字符串替换函数即可:

$args: underline, overline, underline dashed, underline double, underline dotted, underline wavy,
    underline overline;

@each $arg in $args {
    .text-decoration-#{str-replace($arg, ' ', '-')} {
        text-decoration: $arg;
    }
}

兼容旧版本LibSass

如果使用的是旧版不支持内置str-replace的Sass环境,可以先自定义字符串替换函数再使用:

// 自定义字符串替换函数
@function str-replace($string, $search, $replace: '') {
  $index: str-index($string, $search);
  @if $index {
    @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
  }
  @return $string;
}

$args: underline, overline, underline dashed, underline double, underline dotted, underline wavy,
    underline overline;

@each $arg in $args {
    .text-decoration-#{str-replace($arg, ' ', '-')} {
        text-decoration: $arg;
    }
}

运行以上代码即可输出你需要的最终样式效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:39:02