Less的條件表達式
當需要根據表達式,而不是參數的值或數量進行匹配時,條件表達式(Guards)就顯得非常有用。如果你熟悉函數式編程的話,對條件表達式也不會陌生。
為了盡可能地接近CSS的語言結構,Less使用關鍵字 when 而不是 if/else來實現條件判斷,因為 when 已經在CSS的 @media query 特性中被定義。
表達式中可以使用比較運算符、邏輯運算符、或檢查函數來進行條件判斷。
1、比較運算符
Less包含五個比較運算符:<、>、<=、>=、=,可以使用比較運算符(=)來比較數字,字符串、標識符等,而其余的運算符只能與數字一起使用。如,以下Less代碼:
.mixin (@a) when (@a = 20px){
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) when not (@a < 50%) and not (@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:是否為單位。