现场演示:http://codepen.io/KenPowers/pen/Ddfqh
考虑以下LESS代码:
// Hide all list items by default and make internal labels have pointer cursors
li {
display: none;
label {
cursor: pointer;
}
}
// This function generates selectors and corresponding css
.gen (@tag) {
@sel: ~"#@{tag}:checked";
@{sel} {
& ~ ul > li[data-index~=@{tag}] {
display: list-item;
}
& ~ ul > li > label[for=@{tag}] {
color: red;
}
}
}
// Generate required selectors and css
.gen("foo");
.gen("bar");
.gen("baz");
它会生成以下CSS:
li {
display: none;
}
li label {
cursor: pointer;
}
#foo:checked ~ ul > li[data-index~="foo"] {
display: list-item;
}
#foo:checked ~ ul > li > label[for="foo"] {
color: red;
}
#bar:checked ~ ul > li[data-index~="bar"] {
display: list-item;
}
#bar:checked ~ ul > li > label[for="bar"] {
color: red;
}
#baz:checked ~ ul > li[data-index~="baz"] {
display: list-item;
}
#baz:checked ~ ul > li > label[for="baz"] {
color: red;
}
但是,更加压缩的输出可能如下所示:
li {
display: none;
}
li label {
cursor: pointer;
}
#foo:checked ~ ul > li[data-index~="foo"],
#bar:checked ~ ul > li[data-index~="bar"],
#baz:checked ~ ul > li[data-index~="baz"] {
display: list-item;
}
#foo:checked ~ ul > li > label[for="foo"],
#bar:checked ~ ul > li > label[for="bar"],
#baz:checked ~ ul > li > label[for="baz"] {
color: red;
}
有没有办法可以修改原始LESS来生成第二个CSS列表?
答案 0 :(得分:6)
在Less 1.4.0+中,您可以:extend
占位符类:
.dp-list-item {
display: list-item;
}
.label-color {
color: red;
}
// This function generates selectors and corresponding css
.gen (@tag) {
@sel: ~"#@{tag}:checked ~ ul > li";
@{sel} {
&[data-index~=@{tag}]:extend(.dp-list-item){}
& > label[for=@{tag}]:extend(.label-color){}
}
}
// Generate required selectors and css
.gen("foo");
.gen("bar");
.gen("baz");
生成的CSS:
.dp-list-item,
#foo:checked ~ ul > li[data-index~="foo"],
#bar:checked ~ ul > li[data-index~="bar"],
#baz:checked ~ ul > li[data-index~="baz"] {
display: list-item;
}
.label-color,
#foo:checked ~ ul > li > label[for="foo"],
#bar:checked ~ ul > li > label[for="bar"],
#baz:checked ~ ul > li > label[for="baz"] {
color: red;
}
正如您所看到的,唯一的缺点是我用作占位符的两个类都将在生成的CSS中。我相信这不能解决,直到Less实现类似于Sass'placeholder selectors的东西。
PS。为了简洁起见,我省略了全局li
规则,这些规则不属于mixin。
根据OP请求,这里是Sass(具有.scss
语法)等价物:
//placeholder selectors
%dp-list-item {
display: list-item;
}
%label-color {
color: red;
}
// This function generates selectors and corresponding css
@mixin gen($tag) {
##{$tag}:checked ~ ul > li {
&[data-index~=#{$tag}] {
@extend %dp-list-item;
}
& > label[for=#{$tag}] {
@extend %label-color;
}
}
}
// Generate required selectors and css
@each $item in (foo bar baz) {
@include gen($item);
}
生成的CSS:
#foo:checked ~ ul > li[data-index~=foo], #bar:checked ~ ul > li[data-index~=bar], #baz:checked ~ ul > li[data-index~=baz] {
display: list-item;
}
#foo:checked ~ ul > li > label[for=foo], #bar:checked ~ ul > li > label[for=bar], #baz:checked ~ ul > li > label[for=baz] {
color: red;
}
与Less相比,你可以看到Sass的语法相当冗长。 Sass还有一些不错的功能,例如control directives和优秀的interpolation,我在上面的示例中应用了这些功能。