本來說好上周末要出的這一篇結果拖到了現在,公司上需要做一個h5的游戲,最近這一周都在做這個游戲的單機demo,完全沒時間來寫這個文章。昨天算是把demo的大體完成了,今天可以抽出一點時間來整理這一部分。
Mixin Guards(mixin 監控)
帶條件的mixins
當你想要匹配一個表達式的時候,guards是非常有用的。如果你熟悉函數式編程的話,那你很可能已經見過了。
為了盡可能的接近css的聲明性性質,less選擇實現條件化執行的方式,如:在media查詢特性規范的結構中,使用 guards mixins代替if/else語句。
.mixin (@a) when (lightness(@a) >= 50%) {
background-color: black;
}
.mixin (@a) when (lightness(@a) < 50%) {
background-color: white;
}
.mixin (@a) {
color: @a;
}
關鍵在when這個關鍵詞上,when這個關鍵詞定義了監控原則(這里只有一個監控)。如果我們運行以下代碼:
.class1 { .mixin(#ddd) }
.class2 { .mixin(#555) }
編譯為:
.class1 {
background-color: black;
color: #ddd;
}
.class2 {
background-color: white;
color: #555;
}
guard中比較運算符
在guards中可用的運算符為: > , >= , = , =< , < 。此外,關鍵詞true是唯一的真值,下面兩個mixins相等:
.truth (@a) when (@a) { ... }
.truth (@a) when (@a = true) { ... }
除了關鍵詞true以外,任何值都是假的:
.class {
.truth(40); //不會匹配上面聲明的語句
}
你也可以進行參數之間的比較,或者參數和非參數之間進行比較:
@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 }
guard中的邏輯運算符
你可以在guards中使用邏輯運算符,語法是基于css的媒體查詢。
使用關鍵詞 and 去連接guards:
.mixin (@a) when (isnumber(@a)) and (@a > 0) { ... }
你可以模仿 or運算符通過使用逗號將guards進行分隔。如果任何guards被判斷為真,會被進行匹配:
.mixin (@a) when (@a > 10), (@a < -10) { ... }
使用關鍵詞 not 與條件取反
.mixin (@b) when not (@b > 0) { ... }
類型檢查函數(Type Checking Functions)
最后,如果你想要基于類型來匹配mixins的話,你可以使用is函數:
.mixin (@a; @b: 0) when (isnumber(@b)) { ... }
.mixin (@a; @b: black) when (iscolor(@b)) { ... }
下面是基本的類型檢查函數:
- iscolor
- isnumber
- isstring
- iskeyword
- isurl
如果你想要檢查一個值是否在一個特定的單元中(不是當做數字),你可以使用: - ispixel
- ispercentage
- isem
- isunit
有條件的mixins
另外,default函數可以根據其他mixin匹配來進行mixin匹配,您可以使用它創建類似于else或默認語句(分別是if和case結構)的“條件mixin”:
.mixin (@a) when (@a > 0) { ... }
.mixin (@a) when (default()) { ... } // 只有第一個mixin不匹配時才會匹配這個
CSS Guards(css監控)
發布于v1.5.0
guards也可以用在css選擇器上,這是一種語法糖,用于聲明mixin,然后立即調用它。
在1.5.0之前你可能需要這樣做:
.my-optional-style() when (@my-option = true) {
button {
color: white;
}
}
.my-optional-style();
現在你可以直接在樣式中使用guard
button when (@my-option = true) {
color: white;
}
你也可以通過結合這個和&特性,從而實現一個if類型語句,允許組合多個guards:
& when (@my-option = true) {
button {
color: white;
}
a {
color: blue;
}
}