动态调用LESS的mixin

3
如何动态调用一个mixin?
一个使用案例可能是生成一个样式指南:
// The mixin which should be called
.typography-xs(){
  font-family: Arial;
  font-size: 16px;
  line-height: 22px;
}

// The mixin which tries to call typography-xs
.typography-demo(@typographyName, @mixinName) {
  @{typographyName} {
    &:before{content: '@{typographyName}';}
    // Calling the mixin dynamically
    @mixinName();
  }
}

// Example call of .typograhpy-demo
.typography-demo(xs, typography-xs);

Less CSS能否实现这样的动态调用?
1个回答

7

目前你无法按照自己的意愿进行动态调用。但是,你可以使用模式匹配稍微不同的设置,如下所示:

// The mixin which should be called
.typography(xs){
  font-family: Arial;
  font-size: 16px;
  line-height: 22px;
}

// The mixin which tries to call typography-xs
.typography-demo(@typographyName) {
  @{typographyName} {
    &:before{content: '@{typographyName}';}
    // Calling the mixin dynamically
    .typography(@typographyName);
  }
}

// Example call of .typograhpy-demo
.typography-demo(xs);

使用模式匹配,您可以创建其他模式,例如:

.typography(xl){
  font-family: Arial;
  font-size: 32px;
  line-height: 44px;
}

.typography(times){
  font-family: 'Times New Roman';
  font-size: 16px;
  line-height: 22px;
}

现在您可以调用模式xltimes并让它生成代码。实际上,将要在连字符后使用的任何内容(例如您的-xs)以区分各种排版组的名称作为模式匹配mixin的名称。
此外,我建议在@{typographyName}之前添加选择器的方法,像这样:
.typography-demo(@typographyName, @selector: ~".") {
  @{selector}@{typographyName} {
    &:before{content: '@{typographyName}';}
    // Calling the mixin dynamically
    .typography(@typographyName);
  }
}

默认情况下,它会生成一个类,但可以将其转换为 ID 或任何选择器字符串,最多可达到 @{typographyName}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接