你如何动态调用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);

这样的动态调用是否可以用更少的 css 实现?

最佳答案

您目前无法根据需要动态调用。但是,您可以使用 pattern matching 稍微不同地设置它,如下所示:

// 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 )来区分您的各种排版组,并删除连字符并使用该名称作为您的模式以匹配 mixins。

此外,我会添加一种在 @{typographyName} 之前放置选择器的方法,如下所示:
.typography-demo(@typographyName, @selector: ~".") {
  @{selector}@{typographyName} {
    &:before{content: '@{typographyName}';}
    // Calling the mixin dynamically
    .typography(@typographyName);
  }
}

通过这种方式,它默认生成一个类,但可以将其制成 id 或任何选择器字符串,直到 @{typographyName}

关于css - LESS 动态调用 mixin,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21798871/

10-11 23:24
查看更多