函数多次执行定义的较少css变量



我有一个由随机化器函数定义的css变量,我需要这个变量从列表中生成一个随机背景色,每次我进入页面时:

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

然而,每当我在css中使用这个变量时,该函数似乎都会被执行,导致网页上使用了许多不同的颜色。

有没有什么方法可以转义它,并在函数定义变量后将其转换为字符串?

将生成的代码封装在一个mixin中,然后调用该mixin一次似乎解决了这个问题。所以这个:

@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;
}

对我来说,它产生了这个一致的测试css:

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

最新更新