教程 > LESS 教程 > Less 特征 阅读:17

LESS Mixin Guards

如果要匹配表达式上的简单值或参数数量,则可以使用 Guards。 它与 mixin 声明相关联,并包括附加到 mixin 的条件。 每个 mixin 都会有一个或多个用逗号分隔的Guards; 保护必须用括号括起来。 LESS 使用受保护的 mixin 而不是 if/else 语句并执行计算以指定匹配的 mixin。

下表描述了不同类型的 mixins Guard 以及描述。

序号 Guard 类型 描述
1 Guard Comparison Operators 我们可以使用比较运算符 (=) 来比较数字、字符串、标识符等。
2 Guard Logical Operators 我们可以使用 and 关键字来处理带有保护的逻辑运算符。
3 Type Checking Functions 它包含用于确定匹配 mixin 的值类型的内置函数。
4 Conditional Mixins LESS 使用默认函数将 mixin 与其他混合匹配项进行匹配。

示例

以下示例演示了在 LESS 文件中使用 mixin Guard

mixin-guard.html

<!doctype html>
   <head>
      <title>迹忆客(jiyik.com) - 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 迹忆客...</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

style.css

.class1 {
  font-size: 14px;
  color: #FF0000;
}
.class2 {
  font-size: 16px;
  color: #555;
}

按照以下步骤查看上述代码的工作原理

  • 将上述 html 代码保存在 mixin-guard.html 文件中。
  • 在浏览器中打开此 HTML 文件,将显示以下输出。

Less mixin guard

查看笔记

扫码一下
查看教程更方便