是否可以在 LESS 中使用父选择器来指定父属性选择器的值?
我想要以下输出:
[some-attribute] {
font-weight: normal;
}
[some-attribute~="bold"] {
font-weight: bold;
}
给出这个(显然不正确的)例子:
[some-attribute] {
font-weight: normal;
&~="bold" {
font-weight: bold;
}
}
在 LESS 中可以实现这样的功能吗?
编辑:对于任何可能好奇的人,我确实尝试过这种可憎的做法:
[some-attribute {
&] {
font-weight: normal;
}
&~="bold"] {
font-weight: bold;
}
}
我很高兴它没有奏效。我可能受到了诱惑。
最佳答案
Disclaimer: This is strictly how not to over-complicate things but yeah it is still possible in a way using selector interpolation and mixins.
您可以编写如下所示的混入,将属性名称用作一个输入参数,将条件用作另一个输入参数。 condition 是一个可选参数,当它没有被提供时,mixin 认为它只是一个属性存在选择器。
必须附加的规则也作为输入传递。
.mixin-attrib-selector(@attr-name, @rule, @param:null){
@sel-start: ~"[";
@sel-end: ~"]";
@{sel-start}@{attr-name}{
& when(@param = null){
&@{sel-end}{
@rule();
}
}
& when not (@param = null){
&@{param}@{sel-end}{
@rule();
}
}
}
}
.mixin-attrib-selector(some-attribute, {
font-weight: normal;
});
.mixin-attrib-selector(some-attribute,{
font-weight: bold;
}, ~"~='bold'");
#output{
.mixin-attrib-selector(some-attr, {
font-weight: normal;
});
.mixin-attrib-selector(some-attr,{
font-weight: italic;
}, ~"~='italic'");
}
关于css-selectors - 在 LESS 中使用父选择器指定属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30610566/