有什么方法可以仅使用CSS生成给定范围内的随机数? [英] Is there any way to generate a random number within a given range using only CSS?

查看:37
本文介绍了有什么方法可以仅使用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屋!

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