Sass 字符串函数
学习使用 Sass 内置字符串函数进行字符串操作。 · 难度:入门 · +15XP
字符串函数概述
Sass 提供了一系列用于处理字符串的内置函数,包括大小写转换、查找、替换、截取等,方便动态生成样式。
常用字符串函数
| 函数 | 描述 | 示例 |
|---|---|---|
to-upper-case($str) | 转换为大写 | to-upper-case('hello') → 'HELLO' |
to-lower-case($str) | 转换为小写 | to-lower-case('HELLO') → 'hello' |
str-length($str) | 返回字符串长度 | str-length('hello') → 5 |
str-index($str, $substr) | 返回子串首次出现位置(从1开始) | str-index('hello', 'l') → 3 |
str-insert($str, $insert, $index) | 在指定位置插入字符串 | str-insert('helo', 'l', 4) → 'hello' |
str-slice($str, $start, $end) | 截取子串 | str-slice('hello', 2, 4) → 'ell' |
实际应用
$class-name: 'btn-primary';
.#{to-upper-case($class-name)} {
// 生成 .BTN-PRIMARY
}
$name: 'icon-user';
// 检查是否包含 'icon-'
@if str-index($name, 'icon-') == 1 {
.#{$name} {
background-image: url('/icons/' + $name + '.svg');
}
}
字符串拼接
可以使用 + 运算符或插值拼接字符串。
$base: 'button';
$modifier: 'large';
.#{$base}-#{$modifier} {
// .button-large
}练习提示
编写一个函数,接收一个类名并返回其驼峰形式的 CSS 变量名,例如输入 'btn-primary' 返回 '--btnPrimary'。