LESS - Mixin Guards
说明
如果您想在表达式上匹配简单值或参数数量,那么您可以使用 guards。它与 mixin 声明相关联,并包含附加到 mixin 的条件。每个 mixin 将有一个或多个用逗号分隔的 guards;guard 必须用括号括起来。LESS 使用受保护的 mixin 而不是 if/else 语句,并执行计算以指定匹配的 mixin。
下表介绍了不同类型的 mixin guards 及其说明。
Sr.No. | 类型 &描述 |
---|---|
1 | Guard 比较运算符
您可以使用比较运算符 (=) 来比较数字、字符串、标识符等。 |
2 | Guard 逻辑运算符
您可以使用 and 关键字来解决带保护的逻辑运算符问题。 |
3 | 类型检查函数
它包含用于确定要匹配的值类型的内置函数mixins。 |
4 | 条件混合
LESS 使用 default 函数将 mixin 与其他混合匹配项进行匹配。 |
示例
以下示例演示了在 LESS 文件中使用 mixin 保护 −
<!doctype html> <head> <title>Mixin Guards</title> <link rel = "stylesheet" href = "style.css" type = "text/css" /> </head> <body> <h2>Example of Mixin Guards</h2> <p class = "class1">Hello World...</p> <p class = "class2">Welcome to Tutorialspoint...</p> </body> </html>
现在,创建 style.less 文件。
style.less
.mixin (@a) when (lightness(@a) >= 50%) { font-size: 14px; } .mixin (@a) when (lightness(@a) < 50%) { font-size: 16px; } .mixin (@a) { color: @a; } .class1 { .mixin(#FF0000) } .class2 { .mixin(#555) }
您可以使用以下命令将 style.less 编译为 style.css −
lessc style.less style.css
执行上述命令;它将使用以下代码自动创建 style.css 文件 −
style.css
.class1 { font-size: 14px; color: #FF0000; } .class2 { font-size: 16px; color: #555; }
输出
按照以下步骤查看上述代码的工作原理 −
将上述 html 代码保存在 mixin-guard.html 文件中。
在浏览器中打开此 HTML 文件,将显示以下输出。
