Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

css - apply color function on evaluated string color

I have loop in less which is iterating throw numbered variables with colors. It's working fine when I need just evaluate color but not when I want also change color with function.

@cat-1:#c40009;
....

.gen-cats-filter (@index,@prefix) when (@index > 0) {
  .@{prefix}@{index}{
   background-color: ~"@{cat-@{index}}";
   &:hover{
     background-color: darken(~"@{cat-@{index}}", 20%);
   }
  }
  .gen-cats-filter(@index - 1,@prefix);
}
.gen-cats(14,cat);

but this throws error.

is there way how to make it work and on hover make color darker??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Recommended Solution:

Actually, I made the above a lot more complicated than required. A simple option would be to just form the variable name using concatenation and then evaluate it within the darken() function itself instead of using the ~"" (which outputs a String instead of a Color).

&:hover{
   @clr: "@{prefix}-@{index}";
   background-color: darken(@@clr,20%);
}

Original Answer:

Assuming I understood your query correctly, you can achieve it the below way:

@cat-1:#c40009;
@cat-2:#0009c4;

.gen-cats-filter (@index,@prefix) when (@index > 0) {
  .@{prefix}@{index}{
    background-color: ~"@{@{prefix}-@{index}}";
   &:hover{
      @clr: "@{@{prefix}-@{index}}";
      background-color: darken(color(~"`function(){return @{clr}}()`"),20%);
   }
  }
  .gen-cats-filter(@index - 1,@prefix);
}
.gen-cats-filter(2,cat); //I assumed this line was an error in your code and hence modified it.
  1. @clr: "@{@{prefix}-@{index}}"; - Just for reducing the complexity of the next line. This evaluates to "#00c409" for @cat-1.
  2. color(~"`function(){return @{clr}}()`") - Converts the string into a color value that can be used within the darken function.
  3. darken() - Darkens the color value.

CodePen Demo


With recent updates to the Less compiler, we can avoid the JS function bit also and directly write it as follows:

background-color: darken(color(@clr),20%);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...