Sass的函數簡介
在 Sass 中除了可以定義變量,具有 @extend、%placeholder 和 mixins 等特性之外,還自備了一系列的函數功能。其主要包括:
● 字符串函數
● 數字函數
● 列表函數
● 顏色函數
● Introspection 函數
● 三元函數等
當然除了自備的函數功能之外,我們還可以根據自己的需求定義函數功能,常常稱之為自定義函數。
字符串函數
字符串函數顧名思意是用來處理字符串的函數。Sass 的字符串函數主要包括兩個函數:
unquote($string): 刪除字符串中的引號;
quote($string):給字符串添加引號。
1、unquote()函數
unquote() 函數主要是用來刪除一個字符串中的引號,如果這個字符串沒有帶有引號,將返回原始的字符串。
1 //SCSS 2 .test1 {
3 content: unquote('Hello Sass!') ;
4 }
5 .test2 {
6 content: unquote("'Hello Sass!");
7 }
8 .test3 {
9 content: unquote("I'm Web Designer");
10 }
11 .test4 {
12 content: unquote("'Hello Sass!'");
13 }
14 .test5 {
15 content: unquote('"Hello Sass!"');
16 }
17 .test6 {
18 content: unquote(Hello Sass);
19 }
編譯后的 css 代碼:
1 //CSS 2 .test1 {
3 content: Hello Sass!;
4 }
5 .test2 {
6 content: 'Hello Sass!;
7 }
8 .test3 {
9 content: I'm Web Designer;
10 }
11 .test4 {
12 content: 'Hello Sass!';
13 }
14 .test5 {
15 content: "Hello Sass!";
16 }
17 .test6 {
18 content: Hello Sass;
19 }
注意: unquote() 函數只能刪除字符串最前和最后的引號(雙引號或單引號),而無法刪除字符串中間的引號。如果字符沒有帶引號,返回的將是字符串本身。
2、quote()函數
quote() 函數剛好與 unquote() 函數功能相反,主要用來給字符串添加引號。如果字符串,自身帶有引號會統一換成雙引號 ""。
如:
1 //SCSS 2 .test1 {
3 content: quote('Hello Sass!');
4 }
5 .test2 {
6 content: quote("Hello Sass!");
7 }
8 .test3 {
9 content: quote(ImWebDesigner);
10 }
11 .test4 {
12 content: quote(' ');
13 }
編譯出來的 css 代碼:
1 //CSS 2 .test1 {
3 content: "Hello Sass!";
4 }
5 .test2 {
6 content: "Hello Sass!";
7 }
8 .test3 {
9 content: "ImWebDesigner";
10 }
11 .test4 {
12 content: "";
13 }
使用 quote() 函數只能給字符串增加雙引號,而且字符串中間有單引號或者空格時,需要用單引號或雙引號括起,否則編譯的時候將會報錯。
1 .test1 {
2 content: quote(Hello Sass);
3 }
4 //這樣使用,編譯器馬上會報錯:error style.scss (Line 13: $string: ("Hello""Sass") is not a string for `quote')
解決方案就是去掉空格,或者加上引號:
1 .test1 {
2 content: quote(HelloSass);
3 }
4 .test1 {
5 content: quote("Hello Sass");
6 }
同時 quote() 碰到特殊符號,比如: !、?、> 等,除中折號 - 和 下划線_ 都需要使用雙引號括起,否則編譯器在進行編譯的時候同樣會報錯。
字符串函數-To-upper-case()、To-lower-case()
1、To-upper-case()
To-upper-case() 函數將字符串小寫字母轉換成大寫字母。如:
1 //SCSS 2 .test {
3 text: to-upper-case(aaaaa);
4 text: to-upper-case(aA-aAAA-aaa);
5 }
編譯出來的 css 代碼:
1 //CSS 2 .test {
3 text: AAAAA;
4 text: AA-AAAA-AAA;
5 }
2、To-lower-case()
To-lower-case() 函數與 To-upper-case() 剛好相反,將字符串轉換成小寫字母:
1 //SCSS 2 .test {
3 text: to-lower-case(AAAAA);
4 text: to-lower-case(aA-aAAA-aaa);
5 }
編譯出來的 css 代碼:
1 //CSS 2 .test {
3 text: aaaaa;
4 text: aa-aaaa-aaa;
5 }
◑