【问题标题】:LESS variable usage in mixin paramaters在 mixin 参数中使用 LESS 变量
【发布时间】:2012-09-22 05:16:00
【问题描述】:

我希望为边界半径创建 LESS mixin,允许在 mixin 声明中由另外两个参数将两个参数设置为默认值。以下是一个示例,它不起作用,但类似于我想要实现的目标:

.border-radius-ext (@topleft: 0, @topright: 0, @bottomright: @topleft, @bottomleft: @topright) {
    border-top-left-radius: @topleft;
    border-top-right-radius: @topright;
    border-bottom-right-radius: @bottomright;
    border-bottom-left-radius: @bottomleft;
}

我意识到我可以一开始就将所有值设置为 0。那不是我所追求的。我希望如果 mixin 是这样使用的:

blockquote {
    .border-radius-ext(3px, 5px);
}

mixin 会输出:

blockquote {
    border-top-left-radius: 3px;
    border-top-right-radius: 5px;
    border-bottom-right-radius: 3px;
    border-bottom-left-radius: 5px;
}

...如果像这样使用 mixin,仍然允许覆盖 @bottomright@bottomleft 的默认值:

blockquote {
    .border-radius-ext(3px, 5px, 7px, 2px);
}

在这种情况下,输出将是:

blockquote {
    border-top-left-radius: 3px;
    border-top-right-radius: 5px;
    border-bottom-right-radius: 7px;
    border-bottom-left-radius: 2px;
}

LESS 无法做到这一点,还是我做错了?

【问题讨论】:

    标签: css variables parameters less


    【解决方案1】:

    参数的默认值不能是其他参数。但是您可以使用这种方法:

    .border-radius-ext (@topleft, @topright) {
        .border-radius-ext(@topleft, @topright, @topleft, @topright);
    }
    
    .border-radius-ext (@topleft, @topright, @bottomright, @bottomleft) {
        border-top-left-radius: @topleft;
        border-top-right-radius: @topright;
        border-bottom-right-radius: @bottomright;
        border-bottom-left-radius: @bottomleft;
    }
    

    现在您可以使用带有两个或四个参数的 mixin。如果需要,您还可以轻松创建具有三个参数的版本。

    【讨论】:

      【解决方案2】:

      因为您的 mixin 需要 4 个变量 - 您需要输入 4 个。仅当您对所有变量都有默认值并且什么都不传递时,设置默认值才有效 - 或者(我认为) - 如果您总是将变量放在开头,而将默认值放在末尾。

      无论如何,我建议只使用四个变量,可能带有默认值,因为如果另一个开发人员开始使用您的 LESS,它会减少混乱。

      这样的东西会很好:

      .border-radius-ext (@topleft: 0, @topright: 0, @bottomright: 0, @bottomleft: 0) {
          border-top-left-radius: @topleft;
          border-top-right-radius: @topright;
          border-bottom-right-radius: @bottomright;
          border-bottom-left-radius: @bottomleft;
      }
      
      .border-radius-ext(3px, 5px, 7px, 2px);
      

      我还建议使用 LESS 元素,http://lesselements.com/,这是一个很好的预构建 mixin 集合。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-03
        • 1970-01-01
        • 2012-03-18
        • 2017-01-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多