Sass 中定义了各种类型的函数,其中大部分函数咱们能够通过 CSS 语句间接调用。上面是 Sass 中的函数分类:

  • 字符串函数
  • 数字函数
  • 列表函数
  • 映射函数
  • 选择器函数
  • Introspection函数
  • 色彩值函数

本节咱们先来学习字符串相干函数。

字符串函数有哪些

Sass 中的字符串函数用于解决字符串并获取相干信息。有一点须要留神,个别编程语言中字符串的索引都是从 0开始的,然而留神哟,Sass 中字符串的索引是从 1 开始的。

Sass 字符串函数如下所示:

函数形容
quote给字符串增加引号
unquote移除字符串的引号
str-length返回字符串的长度
str-index返回 substring 子字符串第一次在 string 中呈现的地位。
str-insert在字符串 string 中指定索引地位插入内容
str-slice从字符串中截取子字符串,容许设置始末地位,未指定完结索引值则默认截取到字符串开端
to-upper-case将字符串转成大写
to-lower-case将字符串转成小写
unique-id返回一个无引号的随机字符串作为 id

quote函数

quote 函数次要用来给字符串增加引号,如果字符串自身就带有引号,则会默认变为双引号。

示例:

上面这个例子中,定义了两个变量,这两个变量的值都为字符串,其中一个没有带引号,一个带有单引号:

$str1: java;$str2: 'python'; .func1{    content: quote($str1);}.func2{    content: quote($str2);}

编译成 CSS 代码:

.func1 {  content: "java";}.func2 {  content: "python";}

应用 quote() 函数给上述两个字符串增加引号后,不论原来的字符串是带有单引号还是不带引号,最终两个字符串输入后都默认带有双引号。

unquote函数

unquote 函数与 quote 函数性能相同,用于移除字符串所带的引号。

示例:
$str1: "hello,xkd";.func1{    content: unquote($str1);}

编译成 CSS 代码:

.func1 {  content: hello,xkd;}

从输入的 CSS 代码能够看出,通过 unquote() 函数解决的字符串,所带的双引号会被移除。

str-length函数

str-length 函数用于返回字符串的长度。此函数

示例:
.func{    content: str-length("hello, xkd");}

编译成 CSS 代码:

.func {  content: 10;}

从输入的 CSS 代码能够看出,字符串 hello,xkd 的长度为 10,这里须要留神,空格也占一个长度。

str-index函数

str-index 函数用于返回 substring 子字符串第一次在 string 中呈现的地位。其中 substringstring 都为函数参数。如果没有匹配到子字符串,则返回 null

示例:
.func{    content1: str-index(hello, o);    content2: str-index(abc, a);    content3: str-index(kiki, i);}

编译成 CSS 代码:

.func {  content1: 5;  content2: 1;  content3: 2;}

从上述代码中能够看出,当子字符串在字符串中呈现屡次时,例如 kikii 呈现了两次,应用 str-index() 函数后会返回子字符串第一次呈现时所在位置。

str-insert 函数

str-insert 函数用于在字符串 string 中指定索引地位插入内容。第一个参数为字符串,第二个参数为要插入的内容,第三个参数为要插入的地位。

示例:

例如要在 hello, 前面插入 xkd

.func {    content: str-insert("hello,", "xkd", 7);}

编译成 CSS 代码:

.func {  content: "hello,xkd";}

上述代码中,因为 "hello," 字符串的长度为6,如果咱们要在前面插入xkd,就要在 7 的地位插入。

str-slice 函数

str-slice 函数用于从字符串中截取子字符串,容许设置开始和完结地位,当未指定完结索引值时,会默认截取到字符串开端。

示例:
.func {    content: str-slice("abcdefg,", 1, 3);}

编译成 CSS 代码:

.func {  content: "abc";}

上述代码中,截取字符串中1到3之间的子字符串,1示意截取字符串的开始地位,3示意截取字符串完结地位。

to-upper-case/to-lower-case 函数

to-upper-case 函数用于将字符串转成大写,to-lower-case 函数用于将字符串转成小写。

示例:
$str:"Hello, XKD";.func {    content1: to-upper-case($str);    content2: to-lower-case($str);}

编译成 CSS 代码:

.func {  content1: "HELLO, XKD";  content2: "hello, xkd";}

unique-id函数

unique-id 函数返回一个无引号的随机字符串作为 id。

示例:
.func {    content: unique-id();}

编译成 CSS 代码:

.func {  content: uo50mf1eb;}

链接:https://www.9xkd.com/