Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

jquery - Random predefined background color and text color on 2 divs

I am looking to create a Jquery script that will randomly choose a colour from a list of 10, and then apply it as a background color to one div, and the color of a h1 tag.

So far I have this which makes a random color:

$(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);});

but how can I make this choose randomly from a list of 10 colors? I found this, but not sure how you would apply this to bg color div and h1 tag.

$("#controls-wrapper").each(function(){ 
var colors = ["#CCCCCC","#333333","#990099"]; 
var rand = Math.floor(Math.random()*colors.length); 
$(this).css("background-color", colors[rand]);});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think what you are trying to accomplish is this:

Assuming you have a HTML page like this:

<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]);
});

After you have created your colors array you then get a random number corresponding to the index of a color.

Now that you have a random index you can use it to set the background-color, or text color of an object.

If you wanted the colors to be different for each then you would just call

rand = Math.floor(Math.random()*colors.length);

again before setting the color of your next element.

And finally by calling $('h1').css("color", colors[rand]); you will set the color on all H1 elements on the page, you want it to be specific set an ID or class value on the H1 and then use $('h1.myclass').css("color", colors[rand]); OR $('#ID_for_my_H1').css("color", colors[rand]);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...