基于参数存在的条件混合

时间:2013-11-27 09:28:19

标签: less less-mixins

有关如何根据参数存在创建条件mixin的任何建议吗? 例如,我需要验证是否传递了所有参数才能执行某些操作,例如:

.margin (@margintop:0,@marginbottom:0,@marginright:0,@marginleft:0) {

  // if @marginright:0 or @marginleft:0 are passed do that...

  // else...

}

1 个答案:

答案 0 :(得分:6)

1

通常,当您需要为传递的不同数量的参数生成不同的内容时,您根本不需要使用默认参数值,例如:

.margin(@top, @bottom, @right, @left) {
    /* right and left are passed */
}

.margin(@top, @bottom) {
    /* right and left are not passed */
}

.margin() {
    /* no arguments passed */
}

// etc.

请注意,这些mixin中的每一个都可以重用其他的,例如.margin(@top, @bottom)可以为“无左右案例”执行特殊操作,然后调用.margin(@top, @bottom, 0, 0)来执行主要作业。

2

但是如果由于某种原因你仍然需要这些默认值,你可以使用一些不能成为有效边距的特殊默认值,例如:像这样的东西:

.margin(@top: undefined, @bottom: undefined, @right: undefined, @left: undefined) {
    .test-args();

    .test-args() when (@right = undefined) {
        /* right is not passed */
    }
    .test-args() when (@left = undefined) {
        /* left is not passed */
    }

    .test-args()
        when not(@right = undefined)
        and  not(@left  = undefined) {
            /* right and left are passed */
    }

    // etc.
}

3:

第三种选择是使用可变参数并测试它们的计数,但这个是最啰嗦和愚蠢的我猜:

.margin(@args...) {
    .eval-args(length(@args));  // requires LESS 1.5.+
    .eval-args(@nargs) {
        // default values:
        @top:    not passed;
        @bottom: not passed;
        @right:  not passed;
        @left:   not passed;
    }
    .eval-args(@nargs) when (@nargs > 0) {
        @top:    extract(@args, 1);
    }
    .eval-args(@nargs) when (@nargs > 1) {
        @bottom: extract(@args, 2);
    }
    .eval-args(@nargs) when (@nargs > 2) {
        @right:  extract(@args, 3);
    }
    .eval-args(@nargs) when (@nargs > 3) {
        @left:   extract(@args, 4);
    }

    args: @top, @bottom, @right, @left;
}

虽然它可能在某些特殊用例中具有优势。

相关问题