如何用父选择器替换 Less 变量中的“&”?

How do I replace "&" in a Less variable with the parent selector?

我有一个像这样的 Less mixin:http://codepen.io/sirlancelot/pen/QjzzEb?editors=110

// The mixin to toggle containers
#toggle-container(
    @collapsed-selector: ~"&.__collapsible .section--body",
    @expanded-selector: ~"&.__open .section--body"
) {
    @{collapsed-selector}:extend(#section--collapsed) {}
    @{expanded-selector}:extend(#section--expanded) {}
}

我想知道是否可以更改表示法,使参数中的 & 可以扩展到父选择器,就像我将它写在变量之外一样。

如果你在 Codepen 的 CSS 部分点击 "View Compiled" 你会看到 & 被直接输出如下:

#section--collapsed,
.section &.__collapsible .section--body {
    transition: transform ease 250ms;
    transform: scaleY(0);
    transform-origin: top;
    position: absolute;
    width: 100%;
    z-index: 1;
}
#section--expanded,
.section &.__open .section--body {
    transform: scaleY(1);
    position: static;
}

我希望删除 (space)&(space 和符号)。

您可以获得想要的结果,但不能在参数混合参数中包含 &。相反,您需要稍微移动它:

#toggle-container(
    @collapsed-selector: ~".__collapsible .section--body",
    @expanded-selector: ~".__open .section--body"
) {
    &@{collapsed-selector}:extend(#section--collapsed) {}
    &@{expanded-selector}:extend(#section--expanded) {}
}

我做了什么?

  1. 我将 & 移出参数混合参数区域。 为什么? 因为当你 escape a string, variable, or value, it is "used as is with no changes except interpolation 时。”这意味着你的 & 符号被保留 "as is" 并且不允许引用 parent随心所欲。因此...
  2. 我将你的 mixin 参数中的 & 符号移到了你的 ID 的 CSS 中,这样 LESS 就可以引用 child 的 parent(并且可以以所需的方式编译) .