LESS - Mixin 作用域



描述

如果变量直接在调用者的作用域中定义,则无法在调用者的作用域中覆盖它们。但是,变量不受保护,如果在调用者的父作用域中定义,则会被覆盖。

示例

以下示例演示了 LESS 文件中 *mixin 作用域* 的用法:

<html>
   <head>
      <link rel = "stylesheet" href = "style.css" type = "text/css" />
      <title>Mixins Scope</title>
   </head>

   <body>
      <div class = "myclass">
         <h2>Welcome to Tutorialspoint</h2>
         <p>LESS is a CSS pre-processor that enables customizable, 
         manageable and reusable style sheet for web site.</p>
      </div>
   </body>
</html>

接下来,创建 *style.less* 文件。

style.less

@val: 20px; // callers parent scope - no protection
.mixin() {
   @val: 10px;
   @definedOnlyInMixin: 10px;
}

.myclass {
   padding-left: @val * @definedOnlyInMixin;
   .mixin();
}

可以使用以下命令将 *style.less* 编译为 *style.css*:

lessc style.less style.css

执行上述命令;它将自动创建包含以下代码的 *style.css* 文件:

style.css

.myclass {
   padding-left: 100px;
}

输出

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

  • 将上述 html 代码保存到 **less_mixin_as_function_scope2.html** 文件中。

  • 在浏览器中打开此 HTML 文件,将显示以下输出。

LESS Mixin Scope
less_mixins_as_functions
广告
© . All rights reserved.