less css variable defined by function multiple executions

孤街浪徒 提交于 2019-12-11 04:27:59

问题


I have a css variable being defined by a randomizer function, I need this variable to generate a random background color from the list, every time I enter the page:

@all-background-colors: "#7B8AA8,#00ADD5,#E93C43,#FC8383";
@background-color: color(~`@{all-background-colors}.split(',')[Math.floor(Math.random()*@{all-background-colors}.split(',').length)]`);

However it seems that the function gets executed every time I use this variable in my css - resulting in many different colors being used across the web page.

is there any way to escape this and transform the variable to a string one after it's defined by the function?


回答1:


Wrapping the generating code in a mixin, and then calling that mixin once seems to have resolved the issue. So this:

@all-background-colors: "#7B8AA8,#00ADD5,#E93C43,#FC8383";

.generateColor() { /* define mixin */
@background-color: color(~`@{all-background-colors}.split(',')[Math.floor(Math.random()*@{all-background-colors}.split(',').length)]`);
}
.generateColor(); /* call the mixin which sets the variable once */

.test1 {
  color-fixed: @background-color;
}
.test2 {
  color-fixed: @background-color;
}
.test3 {
  color-fixed: @background-color;
}

Which for me produced this consistent test css:

.test1 {
  color-fixed: #7b8aa8;
}
.test2 {
  color-fixed: #7b8aa8;
}
.test3 {
  color-fixed: #7b8aa8;
}


来源:https://stackoverflow.com/questions/17763997/less-css-variable-defined-by-function-multiple-executions

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