LESS - 模式匹配



描述

您可以透過向混合傳遞引數來更改其行為。

考慮一個簡單的 LESS 程式碼片段:

.mixin(@a; @color) { ... }

.line {
   .mixin(@color-new; #888);
}

您可以使用不同的 @color-new 值來建立不同的混合行為,如下面的程式碼所示。

.mixin(dark; @color) {
   color: darken(@color, 15%);
}

.mixin(light; @color) {
   color: lighten(@color, 15%);
}

@color-new: dark;

.line {
   .mixin(@color-new; #FF0000);
}

如果將 @color-new 的值設定為 dark,則它將以較深的顏色顯示結果,因為混合定義將 dark 作為第一個引數匹配。

示例

以下示例演示了在 LESS 檔案中使用模式匹配:

<!doctype html>
   <head>
      <title>Pattern Matching</title>
      <link rel = "stylesheet" href = "style.css" type = "text/css" />
   </head>

   <body>
      <h2>Example of Pattern Matching</h2>
      <p class = "myclass">Welcome to Tutorialspoint...</p>
   </body>
</html>

接下來,建立 style.less 檔案。

style.less

.mixin(dark; @color) {
   color: darken(@color, 15%);
}

.mixin(light; @color) {
   color: lighten(@color, 15%);
}

@color-new: dark;

.myclass {
   .mixin(@color-new; #FF0000);
}

您可以使用以下命令將 style.less 編譯為 style.css

lessc style.less style.css

執行上述命令;它將自動建立 style.css 檔案,其中包含以下程式碼:

style.css

.myclass {
   color: #b30000;
}

輸出

按照以下步驟檢視上述程式碼的工作原理:

  • 將上述 html 程式碼儲存在 pattern-matching.html 檔案中。

  • 在瀏覽器中開啟此 HTML 檔案,將顯示以下輸出。

Pattern Matching
less_parametric_mixins.htm
廣告

© . All rights reserved.