可以通過傳遞參數來改變它混合的行為。
考慮一個簡單的 Less 的代碼片段:
.mixin(@a; @color) { ... } .line { .mixin(@color-new; #888); }
您可以使用 @color-new 不同的值,來設置 mixin 的行為,如下面的代碼。
.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)值,那麼它就會在較暗的顏色顯示的結果作為 mixin 定義黑暗匹配第一個參數。
示例
下麵的例子演示了 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 zaixian zaixian...</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檔,得到如下輸出顯示。
上一篇:
Less高級參數和@rest變數
下一篇:
Less參數化混合