css - LESS 动态调用 mixin

标签 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 进行这样的动态调用?

最佳答案

您目前不能随心所欲地动态调用。但是,您可以使用 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/

相关文章:

html - 具有可变宽度的 tile 的 Flexbox 顺序

html - 自定义 Bootstrap 按钮颜色背景错误的点击

html - 如何使用 px 回退使 Compass Vertical Rhythm 输出 Rems 而不是 Ems?

javascript - 试图理解以工厂和基于函数的混合技术为特征的对象组合模式

css - 嵌套 LESS 到 css 类

html - 使用 Bootstrap 固定导航栏

3D 中的 CSS3 透视图

html - 跨度、输入、跨度 100% 宽度 CSS 问题

css - 如何在 Genesis Framework 中应用 Less css

javascript - Lightning 生成的 html 列表水平对齐问题