JQuery随机背景颜色和颜色,在2 div的 [英] JQuery Random Background color and color, on 2 div's

查看:250
本文介绍了JQuery随机背景颜色和颜色,在2 div的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要创建一个Jquery脚本,它将从10列表中随机选择一种颜色,然后将其作为背景颜色应用于一个div,以及h1标签的颜色。

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

但是如何从10种颜色的列表中随机选择?
我发现这个,但不知道如何将它应用到bg color div和h1标签。

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


推荐答案

我认为你想要完成的是:

I think what you are trying to accomplish is this:

假设您有这样的HTML页面:

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.

最后通过调用 $('h1')。css(color,colors [rand]); 你将设置页面上所有H1元素的颜色,你希望它是特定的在H1上设置一个ID或类值,然后使用 $('h1.myclass')css (color,colors [rand]); OR $('#ID_for_my_H1' c>

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

这篇关于JQuery随机背景颜色和颜色,在2 div的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆