我想创建一个 Jquery 脚本,该脚本将从 10 种颜色的列表中随机选择一种颜色,然后将其作为背景色应用到一个 div 和 h1 标签的颜色。
到目前为止,我有这个可以生成随机颜色:
$(document).ready(function() { var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ','
+ (Math.floor((256-199)*Math.random()) + 200) + ','
+ (Math.floor((256-199)*Math.random()) + 200) + ')';
$('#controls-wrapper').css("background-color", hue);
$('h1').css("color", hue);});
但是我怎样才能让它从 10 种颜色的列表中随机选择呢? 我找到了这个,但不确定如何将其应用于 bg color div 和 h1 标签。
$("#controls-wrapper").each(function(){
var colors = ["#CCCCCC","#333333","#990099"];
var rand = Math.floor(Math.random()*colors.length);
$(this).css("background-color", colors[rand]);});
最佳答案
我认为您要完成的是:
假设您有一个这样的 HTML 页面:
<html>
<body>
<h1>Hello World!</h1>
<div id="controls-wrapper>some text</div>
</body>
$(document).ready(function(){
var colors = ["#CCCCCC","#333333","#990099"];
var rand = Math.floor(Math.random()*colors.length);
$('#controls-wrapper').css("background-color", colors[rand]);
$('h1').css("color", colors[rand]);
});
创建颜色数组后,您将获得一个对应于颜色索引的随机数。
现在您有了一个随机索引,您可以使用它来设置对象的背景颜色或文本颜色。
如果你想让每种颜色都不同,那么你只需调用
rand = Math.floor(Math.random()*colors.length);
再次设置下一个元素的颜色。
最后通过调用 $('h1').css("color", colors[rand]);
您将设置页面上所有 H1 元素的颜色,您希望它具体在 H1 上设置 ID 或类值,然后使用 $('h1.myclass').css("color", colors[rand]);
或 $('# ID_for_my_H1').css("color", colors[rand]);
关于jquery - 2 个 div 上的随机预定义背景颜色和文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5897573/