较少的css变量,由函数多次执行定义 [英] less css variable defined by function multiple executions

查看:71
本文介绍了较少的css变量,由函数多次执行定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)]`);

但是,似乎每次我在CSS中使用此变量时都会执行该函数-导致整个网页使用许多不同的颜色.

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?

推荐答案

将生成的代码包装在mixin中,然后调用该mixin似乎已解决了该问题.因此:

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

对我来说,这产生了一致的测试CSS:

Which for me produced this consistent test css:

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

这篇关于较少的css变量,由函数多次执行定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆