【问题标题】:LESS call a mixin dynamicallyLESS 动态调用 mixin
【发布时间】:2014-03-14 23:10:50
【问题描述】:

如何动态调用 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 就可以实现这样的动态调用吗?

【问题讨论】:

    标签: css less mixins


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-14
      • 2013-06-10
      • 2012-09-24
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多