使用JQuery将三种不同的背景颜色应用于具有相同类的三个div

时间:2013-01-18 16:25:43

标签: jquery css background-color

  

可能重复:
  Apply different background color using jquery

我在页面上有三个div,都是类.contact-image

我希望这三个div具有不同的背景颜色(青色,黄色,洋红色) - 理想的rgb颜色,透明度为50%。它们不需要随机选择 - 如下所示是好的。     一(品红)     二(青色)     三(黄色)

我是JQuery的新手,到目前为止,我已经从这里得到了一个类似问题的答案。

$(function() {
$(".contact-image").each(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) + ')';
     $(this).css("background-color", hue);
});

});

这会使所有3个div颜色随机变成不同的颜色,但我没有根据我的需要调整它的知识。任何帮助将非常感谢..

3 个答案:

答案 0 :(得分:6)

您可以使用函数setter语法:

$(".contact-image").css("background-color", function(i) {
  return ["magenta", "cyan", "yellow"][i];  // one of the three
});

答案 1 :(得分:0)

$(function() {
    var colors = ['magenta', 'cyan', 'yellow'];
    $(".contact-image").each(function(i) {
        $(this).css("background-color", colors[i]);
    })
});

答案 2 :(得分:0)

这样做的一种方法是你可以通过div本身的十六进制值设置颜色:

HTML:

<div class="contact-image" data-color="ffffff">
  Content 1
</div>
<div class="contact-image" data-color="ff0000">
  Content 2
</div>
<div class="contact-image" data-color="000000">
  Content 3
</div>

JQuery的:

$(function() {
  $(".contact-image").each(function() {
      var hue = "#"+$(this).data('color');
       $(this).css("background-color", hue);
  });
});
相关问题