CSS中是否有办法让它从数组中选择一种随机字体颜色?我知道我可以用服务器端或javascript做到这一点,但我想知道是否有纯CSS方式来做到这一点。
答案 0 :(得分:35)
CSS表达式(允许通过CSS获得动态脚本内容)与Web窗体一起在低效率地狱中被抛弃,只有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>
答案 1 :(得分:22)
这在CSS中是不可能的,这是确定性的。但是,您可以使用客户端JavaScript执行此操作:
var colors = ['#ff0000', '#00ff00', '#0000ff'];
var random_color = colors[Math.floor(Math.random() * colors.length)];
document.getElementById('title').style.color = random_color;
如果你正在使用jQuery,最后一行可能会变成
$('#title').css('color', random_color);
答案 2 :(得分:2)
使用JQuery在JavaScript中很简单。
您可以执行以下操作:
var hexArray = ['#hexVal','#hexVal','#hexval', '#hexval']
var randomColor = hexArray[Math.floor(Math.random() * hexArray.length)];
$("#divId").css("color",randomColor); //A class selector would work too
每次刷新页面时都会选择一种新颜色。
答案 3 :(得分:1)
这就是我做到的。
第一部分是连续顺序,元素1获得颜色1等。
然后,当你没有颜色时,它会随机化它。
//Specify the class that you want to select
var x = document.getElementsByClassName("ms-webpart-chrome-title");
var i;
var c;
//specify the colors you want to use
var colors = ["#009933", "#006699", "#33cccc", "#99cc00", "#f60"];
var d = colors.length;
for (i = 0; i < x.length; i++){
while (i < d) {
c = i;
var random_color = colors[c];
x[i].style.borderTopColor = random_color;
i++;
}
while (i >= d) {
var random_color = colors[Math.floor(Math.random() * colors.length)];
x[i].style.borderTopColor = random_color;
i++;
}
}
答案 4 :(得分:0)
不使用预定义颜色集,以获得均匀随机化的颜色函数
function randomColor(){
rc = "#";
for(i=0;i<6;i++){
rc += Math.floor(Math.random()*16).toString(16);
}
return rc;
}
或内联
"#"+Math.floor(Math.random() * 0x1000000).toString(16)