简体   繁体   English

如何在LESS中的变量中使用变量名?

[英]How can I have a variable name in a variable in LESS?

I have this code snippet: 我有这段代码:

// Color settings 
.setCat(@x) {
    .cat@{x} {
        .menu-link {
            &.selected, &:hover { background: ~@{"catColor@{x}"}; }
            &:hover:after { border-top-color: ~@{"catColor@{x}"}; }
            &:only-child:after { border-top-color: transparent; }
        }
        .menu-link-submenu { background: ~@{"catColor@{x}"}; }
    }
}

.setCat(1);

I hope you can see what I am trying to do. 我希望你能看到我想做的事情。 I want the @catColor1 output which LESS then will compile into my hex color stored in that variable. 我想要@catColor1输出,然后LESS将编译成存储在该变量中的十六进制颜色。

Is this possible? 这可能吗? Is there a better way? 有没有更好的办法?

You need to nest both calls into the string. 您需要将两个调用嵌套到字符串中。 I've made the processing all go through a single new variable useColor (which you do not have to do , I just think it looks cleaner): 我已经完成了处理,只需要一个新的变量useColor (你不必这样做 ,我觉得它看起来更干净):

.setCat(@x) {
    .cat@{x} {
        @useColor: ~"@{catColor@{x}}";
        .menu-link {
            &.selected, &:hover { background: @useColor; }
            &:hover:after { border-top-color: @useColor; }
            &:only-child:after { border-top-color: transparent; }
        }
        .menu-link-submenu { background: @useColor; }
    }
}

So assuming this LESS: 所以假设没有:

@catColor1: #fff;
@catColor2: #aaa;

.setCat(1);
.setCat(2);

Produces this CSS: 生成这个CSS:

.cat1 .menu-link.selected,
.cat1 .menu-link:hover {
  background: #ffffff;
}
.cat1 .menu-link:hover:after {
  border-top-color: #ffffff;
}
.cat1 .menu-link:only-child:after {
  border-top-color: transparent;
}
.cat1 .menu-link-submenu {
  background: #ffffff;
}
.cat2 .menu-link.selected,
.cat2 .menu-link:hover {
  background: #aaaaaa;
}
.cat2 .menu-link:hover:after {
  border-top-color: #aaaaaa;
}
.cat2 .menu-link:only-child:after {
  border-top-color: transparent;
}
.cat2 .menu-link-submenu {
  background: #aaaaaa;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM