我有一个由随机函数函数定义的css变量,我需要这个变量从列表中生成随机背景颜色,每次我进入页面:
@all-background-colors: "#7B8AA8,#00ADD5,#E93C43,#FC8383";
@background-color: color(~`@{all-background-colors}.split(',')[Math.floor(Math.random()*@{all-background-colors}.split(',').length)]`);
Run Code Online (Sandbox Code Playgroud)
然而,似乎每次在我的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;
}
Run Code Online (Sandbox Code Playgroud)
哪个对我来说产生了这个一致的测试css:
.test1 {
color-fixed: #7b8aa8;
}
.test2 {
color-fixed: #7b8aa8;
}
.test3 {
color-fixed: #7b8aa8;
}
Run Code Online (Sandbox Code Playgroud)