CSS从数组中选择一种随机颜色

Saq*_*Ali 18 html css html5 css3

CSS中是否有一种方法可以让它从数组中选择一种随机字体颜色?我知道我可以用服务器端或javascript做到这一点,但我想知道是否有纯CSS方式来做到这一点.

Exp*_*lls 44

CSS表达式(通过CSS允许动态脚本内容)是与Web Forms一起在低效率地狱中流淌的可憎之物,只有IE7及以下版本才支持.但既然你问过.

<style>
blink marquee {
   color: expression("rgb(" + Math.floor(Math.random() * 255)
      + "," + Math.floor(Math.random() * 255) + ","
      + Math.floor(Math.random() * 255) + ")");
}
</style>
<blink>
   <marquee>
      color me beautiful
   </marquee>
</blink>
Run Code Online (Sandbox Code Playgroud)

  • 你是个怪物! (26认同)
  • @abbood 如果这仅适用于 IE7 及更低版本,这怎么是正确的答案? (2认同)
  • 大帐是讽刺的.我不敢相信马戏团仍在工作. (2认同)

bde*_*ham 28

这在CSS中是不可能的,这是确定性的.但是,您可以使用客户端JavaScript执行此操作:

var colors = ['#ff0000', '#00ff00', '#0000ff'];
var random_color = colors[Math.floor(Math.random() * colors.length)];
document.getElementById('title').style.color = random_color;
Run Code Online (Sandbox Code Playgroud)

如果您正在使用jQuery,最后一行可能会成为

$('#title').css('color', random_color);
Run Code Online (Sandbox Code Playgroud)

  • @abbood Explosion Pills 的回答很有趣,但是:“仅 IE7 及以下版本支持”。这不是解决 OP 问题的现实方法。 (2认同)
  • 我不建议在 IE7 及以下开始使用它们 (2认同)