有什么方法可以仅使用CSS生成给定范围内的随机数? [英] Is there any way to generate a random number within a given range using only CSS?
问题描述
例如,类似:
div {左边距:随机(-100,100);}
在纯CSS中目前尚无此方法,但是,如果您使用的是CSS预处理器,例如 LESS将评估JavaScript表达式./p>
如果要将其分解为随机的mixin/函数,可以使用:
.random(@min,@max){@random:`Math.round(Math.random()*(@ {max}-@ {min})+ @ {min}))`;}div {.random(-100,100);左边距:〜'@ {random} px';}
每次都会使用不同的 margin-left
值进行编译:
div {左边距:18px;}
但是,我不确定在生产环境中这将是多么实用,因为您的CSS 应该已经被编译/最小化,而不是即时编译.因此,您应该只使用简单的JavaScript即可实现这一目标.
For example, something like:
div {
margin-left: random(-100, 100);
}
There is currently no way to do this in pure CSS, however if you're using a CSS pre-processor, such as LESS, then you can do the following:
@randomMargin: `Math.round(Math.random() * 100)`;
div {
margin-left: ~'@{randomMargin}px';
}
The reason this works is because LESS will evaluate JavaScript expressions.
If you want to break it into a random mixin/function, you could use:
.random(@min, @max) {
@random: `Math.round(Math.random() * (@{max} - @{min}) + @{min})`;
}
div {
.random(-100, 100);
margin-left: ~'@{random}px';
}
Which will compile with a different margin-left
value each time:
div {
margin-left: 18px;
}
However, I am not sure how practical this would be in a production environment since your CSS should already be compiled/minified rather than compiled on the fly. Therefore you should just use straight JavaScript in order to achieve this.
这篇关于有什么方法可以仅使用CSS生成给定范围内的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!