少动态调用mixin

时间:2014-02-15 14:34:10

标签: css less mixins

如何动态调用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进行?

1 个答案:

答案 0 :(得分:7)

您目前无法根据需要动态调用。但是,您可以使用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)来区分各种排版组,并删除连字符并使用该名称作为模式以匹配mixin。

此外,我还会添加一种方法,将选择器放在@{typographyName}之前,如下所示:

.typography-demo(@typographyName, @selector: ~".") {
  @{selector}@{typographyName} {
    &:before{content: '@{typographyName}';}
    // Calling the mixin dynamically
    .typography(@typographyName);
  }
}

这种方式默认情况下会生成一个类,但可以创建一个id或任何选择器字符串,直到@{typographyName}