1. 程式人生 > >less 新手入門(四)—— Mixin Guards

less 新手入門(四)—— Mixin Guards

四、Mixin Guards

有條件的 mixin

當您想要匹配表示式時,相對於簡單的值或特性,Guards 是有用的。如果您熟悉函數語言程式設計,您可能已經遇到過它們。

為了儘可能地保持 CSS 的宣告性質,在 @ media 查詢特性規則中,Less 選擇通過保護的 mixin 而不是 if/ elsestatements 來執行條件執行。

.mixin (@a) when (lightness(@a) >= 50%){
    background-color: black;
}

.mixin(@a) when (lightness(@a) < 50%)
{ background-color: white; } .mixin(@a){ color: @a; }

關鍵字是 when 關鍵字,它引入了一個守衛序列 (這裡只有一個 guard)。現在,如果我們執行以下程式碼:

.class1 { .mixin(#ddd) }
.class2 { .mixin(#555) }

輸出:

.class1 {
  background-color: black;
  color: #ddd;
}
.class2 {
  background-color: white;
  color: #555;
}

8.1 guard 比較運算子

在 guard 可用的比較操作符的完整列表為:>、> =、=、<、<、<。另外,關鍵字 true 是唯一的 truthy 值,判斷是否這兩個引數值相等:

.truth(@a) when (@a){ 
    font-size: 12px;
}

.truth(@a) when (@a = true){
    font-size: 26px;
}

除了關鍵字 true 以外的任何值都是假的:

?

| 123 | .class``3``{``.truth(``40``); // 不會匹配到上面任何一個``} |

守衛可以用逗號分開,如果任何一個判斷語句的計算結果為真,它被認為是一種匹配:

.mixin (@a) when (@a > 10), (@a < -10) { ... }

注意,您還可以比較彼此的引數,或者用非引數進行比較

@media: mobile;

.mixin (@a) when (@media = mobile) { ... }
.mixin (@a) when (@media = desktop) { ... }

.max (@a; @b) when (@a > @b) { width: @a }
.max (@a; @b) when (@a < @b) { width: @b }

8.2 型別檢查功能

最後,如果想要根據值的型別來匹配 mixin,可以使用 is 函式

.mixin (@a; @b: 0) when (isnumber(@b)) { ... }
.mixin (@a; @b: black) when (iscolor(@b)) { ... }

下面是一些基本型別檢查函式:

  • iscolor
  • isnumber
  • isstring
  • iskeyword
  • isurl

如果您想要檢查一個值是否在一個特定的單元中,除了作為一個數字之外,您可以使用其中一個:

  • ispixel
  • ispercentage
  • isem
  • isunit

8.3 有條件的混合

此外,default 函式可以用於根據其他混合匹配建立 mixin 匹配,您可以使用它來建立類似於 else 或 default 語句的 “條件混合”(if 和 case 結構)。

.mixin (@a) when (@a > 0) { ...  }
.mixin (@a) when (default()) { ... } // matches only if first mixin does not, i.e. when @a <= 0

最後但並非最不重要的是,您可以使用 and 關鍵字來為一個警衛提供額外的條件:

.mixin (@a) when (isnumber(@a)) and (@a > 0) { ... }

最後,not 關鍵字的否定條件:

.mixin (@b) when not (@b > 0) { ... }