在 CSS 中是否有一种方法可以从数组中随机选择字体颜色?我知道可以通过服务器端或 JavaScript 实现此操作,但我想知道是否有纯 CSS 的方法。
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>
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);
使用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
//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++;
}
}
不使用预定义的颜色集,以获得统一随机化颜色函数
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)
li:nth-child(6n) { background-color: rgb(249, 195, 141);}
li:nth-child(6n+1) { background-color: rgb(173, 255, 173);}
li:nth-child(6n+2) { background-color: rgb(255, 255, 203);}
li:nth-child(6n+3) { background-color: rgb(166, 197, 255);}
li:nth-child(6n+4) { background-color: rgb(244, 197, 242);}
li:nth-child(6n+5) { background-color: rgb(255, 174, 178);}
当然,这不是真正的数学随机,但是如果与页面中可见数字相比有足够多的颜色,读者会失去追踪,并产生接近随机的印象。
更多信息请参见:{{link1:使用模运算符的nth-child}}