如何在 Less 中传递带逗号的参数

How to Pass Parameters with Commas in Less

我有一个 mixin,它采用形状的名称及其坐标。我想知道如果坐标包含逗号,我将如何传递我的坐标?

.clip-path(@shape @coords) {
    -webkit-clip-path: @shape(@coords);
       -moz-clip-path: @shape(@coords);
            clip-path: @shape(@coords);
}

.foo {
  .clip-path(polygon, 0 0, 0 100%, 100% 0);

  /*
     I am trying to achieve:
     clip-path: polygon(0 0, 0 100%, 100% 0);
  */
}

一种解决方法是使用临时变量:

.foo {
  @workAround: 0 0, 0 100%, 100% 0;
  .clip-path(polygon, @workAround);
}

你也可以在将变量传递给 mixin 时转义值:

.foo {
  .clip-path(polygon, ~"0 0, 0 100%, 100% 0");
}

这些都确保传递给 mixin 的值是一个字符串。

Note: I second all comments made by torazaburo. Please don't use Less mixins as a way to add prefixes. It is much more simpler to use a prefixing tool like AutoPrefixer or Prefix-free.

也就是说,您可以通过以下几种方式获得所需的输出:

.clip-path(@shape, @coords) {
  -webkit-clip-path: ~"@{shape}(@{coords})";
  -moz-clip-path: ~"@{shape}(@{coords})";
  clip-path: ~"@{shape}(@{coords})"; /* use interpolation to display the output */
}

.foo {
  .clip-path(polygon, ~"0 0, 0 100%, 100% 0"); /* pass the values as one single string */
}

或者,使用如下所示的 advanced @rest variable option。这是一种将可变数量的 args 传递给 mixin 并仍然使其与 mixin 定义匹配的方法。

.clip-path(@shape; @coords...) {
  -webkit-clip-path: ~"@{shape}(@{coords})";
  -moz-clip-path: ~"@{shape}(@{coords})";
  clip-path: ~"@{shape}(@{coords})";
}

.foo {
  .clip-path(polygon; 0 0, 0 100%, 100% 0);
}
.foo2 {
  .clip-path(polygon; 0 0, 0 100%, 100% 0, 100% 100%); /* Less compiler will pick all values after the first as coords */
}

或者,如果 mixin 只是为了添加供应商前缀(如前所述,我不推荐这样做),最简单的选择如下:

.clip-path(@args) {
  -webkit-clip-path: @args;
  -moz-clip-path: @args;
  clip-path: @args;
}

.foo {
  .clip-path(~"polygon(0 0, 0 100%, 100% 0)"); /* just pass the whole thing as a string */
}