less css calling dynamic variables from a loop

亡梦爱人 提交于 2019-12-30 09:55:21

问题


What I'm trying to do: I have (for now) 7 colors as variables. I want to be able to use them at several places and iterate throught them.

This is what I have that don't work

@color1:#06A1C0;
@color2:#8F4F9F;
@color3:#ED1D24;
@color4:#5A9283;
@color5:#B38C51;
@color6:#EC008C;
@color7:#8F4F9F;

@iterations: 8;
.mixin-loop (@index) when (@index > 0) {
color@{index}:hover{
  @tmp: ~'@color';
  @num: @index;
      color: @tmp@num;
  }

.mixin-loop(@index - 1);
}
.mixin-loop (0) {}
.mixin-loop(@iterations);

What I need I want this as a result

.color1:hover{color#06A1Co}
.color2:hover{color#8F4F9F}
etc..

What's the problem? I can't find a way to evalute @tmp@num to get the actual variable.

UPDATE Perfect answer provided by Ash Hitchcock below.


回答1:


I have just been trying todo the same thing today with LESS. The solution I came up with is to use a Parametric Mixin to create (define) the variable, see updated exmaple:

@color1:#06A1C0;
@color2:#8F4F9F;
@color3:#ED1D24;
@color4:#5A9283;
@color5:#B38C51;
@color6:#EC008C;
@color7:#8F4F9F;

@iterations: 7;

.define(@var) {
  @colorSet: 'color@{var}';
}


.mixin-loop (@index) when (@index > 0) {
color@{index}:hover{
    .define(@index);
    color:  @@colorSet;
  }

.mixin-loop(@index - 1);
}
.mixin-loop (0) {}
.mixin-loop(@iterations);

Hope this helps.




回答2:


Why don't you use them in your CSS file? Why are you trying them in your File? its not a great idea.
Using the CSS for each DIV will be good. Give it a class with the code Like:

<div class='@if(condition == true) {"thisclass"} else {"thatclass"}'></div>

And just use one CSS for all the conditions. That would be simple.



来源:https://stackoverflow.com/questions/18272285/less-css-calling-dynamic-variables-from-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!