Less的條件表示式Guards
阿新 • • 發佈:2019-02-13
當需要根據表示式,而不是引數的值或數量進行匹配時,條件表示式(Guards)就顯得非常有用。如果你熟悉函數語言程式設計的話,對條件表示式也不會陌生。
為了儘可能地接近CSS的語言結構,Less使用關鍵字 when 而不是 if/else來實現條件判斷,因為 when 已經在CSS的 @media query 特性中被定義。
表示式中可以使用比較運算子、邏輯運算子、或檢查函式來進行條件判斷。
1、比較運算子
Less包含五個比較運算子:<、>、<=、>=、=,可以使用比較運算子(=)來比較數字,字串、識別符號等,而其餘的運算子只能與數字一起使用。如,以下Less程式碼:
.mixin
color:red;
}
.mixin (@a)when(@a<20px){
color:blue;
}
.mixin (@a){
font-size:@a;
}
h2 {
.mixin(20px)
}
編譯後的CSS程式碼為:
h2 {
color: red;
font-size:20px;
}
此外,還可以使用關鍵字true,它表示布林真,以下兩個mixin是相同的:
.truth (@a)when(@a){...}
.truth (@a)when(@a=true){...}
在Less中,只有 true 表示布林真,關鍵字true以外的任何值,都被視為布林假。如:
.class{
.truth(40);// 不會匹配以上任何定義
}
Less中,Guards可以是多個表示式,多個表示式之間,使用逗號‘,’分隔。如果其中任意一個表示式的結果為 true,則匹配成功,這就相當於“或”的關係。如:
.mixin (@a)when(@a<-10),(@a>10){
width:100px;
}
上述Guards就表示: [-10,10] 之間的值將匹配失敗,其餘均匹配成功。比如以下呼叫,.class1 和 .class3 會匹配成功,.class2 將匹配失敗:
.class1 {
.mixin(-20);
}
.class2 {
.mixin(0);
}
.class3 {
.mixin(20
}
編譯後的CSS程式碼為:
.class1 {
width:100px;
}
.class3 {
width:100px;
}
2、邏輯運算子
Less中,Guards也可以使用 and 和 not 來進行邏輯運算。如,以下Less程式碼:
.mixin (@a)when(@a>50%)and(@a>5px){
font-size:14px;
}
.mixin (@a)whennot(@a<50%)andnot(@a<5px){
font-size:20px;
}
.mixin (@a){
color:@a;
}
.class1 {
.mixin(#FF0000)
}
.class2 {
.mixin(#555)
}
編譯後的CSS程式碼為:
.class1 {
color:#ff0000;
}
.class2 {
color:#555555;
}
3、檢查函式
如果想基於值的型別、或特定的單位進行匹配,就可以使用 is* 函式。如:
.mixin (@a,@b:0)when(isnumber(@a)){...}
.mixin (@a,@b: black)when(iscolor(@b)and(@a>0)){...}
以下是常見的型別檢查函式:
- Iscolor:是否為顏色值。
- Isnumber:是否為數值。
- Isstring:是否為字串。
- Iskeyword:是否為關鍵字。
- Isurl:是否為URL字串。
- 以下是常見的單位檢查函式:
- Ispixel:是否為畫素單位。
- ispercentage:是否為百分比。
- isem:是否為em單位。
- isunit:是否為單位。