Less從入門到精通——條件表達式(附學習視頻、源碼及筆記)

完整學習視頻及資料在這裏哦~
連接:https://pan.baidu.com/s/1cXs9KKoIFP1M5oTClSr7yg
提取碼:4k8thtml

條件表達式

  • 當須要根據表達式,而不是參數的值或數量來進行匹配時,就須要用到條件表達式了。
  • Less中使用關鍵字 when 來實現條件判斷。
  • 表達式中能夠使用比較運算符、邏輯運算符、或檢查函數來進行條件判斷。

比較運算符

有:>, >= , < , =< , = , ture;函數

.mixin(@width) when (@width <= 360px) {
    width: @width;
    height: 100%;
    background-color: pink;
}
.mixin(@width) when (@width > 360px) {
    width: @width;
    height: 100%;
    background-color: black;
}
div{
    .mixin(500px);
}
// 輸出  匹配到第二個的條件 執行第二個
div {
  width: 500px;
  height: 100%;
  background-color: black;
}

還能夠使用關鍵字true,它表示布爾真,如下兩個mixin是相同的:學習

  • .truth (@a) when (@a) { ... }
  • .truth (@a) when (@a = true) { ... }

在Less中,只有 true 表示布爾真,關鍵字true之外的任何值,都被視爲布爾假。如:url

.div{
    .truth(40);   	// 不會匹配上面的任何定義
}

注意:when後的條件表達式能夠是多個表達式,多個表達式之間使用逗號相隔,若其中任何一個爲true,則匹配爲成功,至關於「 或 」 的關係。code

邏輯運算符

  • Less中,表達式之間也能夠使用and 和 not 來進行邏輯運算。
  • and 鏈接的表達式需都爲 true 才能匹配成功。
  • not 表示否認的意思 至關於「 非 」
// 傳入的參數大於200px 且 小於 500px
.mixin(@width) when (@width > 200px) and (@width < 500px){
    width: @width;
    height: 100%;
    background-color: pink;
}
// 傳入的參數 不小於500px 且 大於0
.mixin(@width) when not(@width < 500px) and (@width > 0){
    width: @width;
    height: 100%;
    background-color: black;
}
div{
    .mixin(500px);
}
// 輸出爲 匹配到第二個
div {
  width: 500px;
  height: 100%;
  background-color: black;
}

總結:逗號——或 , and——與 ,not——非。視頻

類型檢查函數

能夠基於值的類型來匹配函數htm

類型檢查函數 說明
iscolor 是否爲顏色值
isnumber 是否爲數值
isstring 是否爲字符串
iskeyword 是否爲關鍵字
isurl 是否爲URL字符串

是則爲 true 則執行匹配的內容,用於匹配相同的類型。blog

.mixin(@a) when (iscolor(@a)) {
    background-color: @a;
}
.mixin(@a) when (isnumber(@a)) {
    width: @a;
    height: @a;
}
div{
    .mixin(100%);
    .mixin(pink);
}
// 輸出爲 
div {
  width: 100%;
  height: 100%;
  background-color: pink;
}

單位檢查函數

單位檢查函數 說明
ispixel 是否爲像素單位
ispercentage 是否爲百分比
isem 是否爲em單位
isunit 是否爲單位

同類型檢查函數,用於匹配相同的單位。字符串

.mixin(@a) when (ispixel(@a)) {
    border: @a solid pink;
}
.mixin(@a) when (ispercentage(@a)) {
    width: @a;
    height: @a;
}
div{
    .mixin(100%);
    .mixin(1px);
}
// 輸出爲
div {
  width: 100%;
  height: 100%;
  border: 1px solid pink;
}

參考博客:http://www.javashuo.com/article/p-dxcaxzyv-nx.htmlget

相關文章
相關標籤/搜索