为数组中的类分配背景色

时间:2019-07-18 14:46:57

标签: javascript css arrays

我在页面上有六个div,每个div具有相同的类。我试图给它们每个分配一种我在数组中选择的唯一颜色。我不希望它们具有相同的颜色。

我已经成功地为每个div分配了数组的背景色,但是,由于当前它们只是从数组中随机选择颜色,因此某些类可以获得相同的背景色。

Observable<Timeformat>

然后html就像

jQuery(document).ready(function($) {
$(".et_pb_post").each(function() {
  var colors = ["#CFEAEA ","#c9e3d5","#e7dadd","#dde9eb","#ecfac7","#facba9","#dfdbd3","#f1fdc1"];                
  var rand = Math.floor(Math.random()*colors.length);    
    $(this).css("background-color", colors[rand]);
});
});

如何确保所有背景颜色都是唯一的?

非常感谢!

5 个答案:

答案 0 :(得分:1)

我建议您首先按照

中所述的随机值对数组进行混洗

How to randomize (shuffle) a JavaScript array?

然后,只要您使用数组中的值,就可以使用pop()(或shift())将其从数组中删除。

这样,您可以确保数组中的每个值仅使用一次。

答案 1 :(得分:1)

您可以执行以下操作:创建colors数组的副本,并在为div选择颜色时从其中删除颜色:

jQuery(document).ready(function($) {
  var colors = ["#CFEAEA ", "#c9e3d5", "#e7dadd", "#dde9eb", "#ecfac7", "#facba9", "#dfdbd3", "#f1fdc1"];

  var copy = [...colors];

  $(".et_pb_post").each(function() {

    var rand = Math.floor(Math.random() * copy.length);
    $(this).css("background-color", copy[rand]);

    copy = copy.filter(color => color !== copy[rand]);

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="et_pb_post">Some content with bg-color A</div>
<div class="et_pb_post">Some content with bg-color B</div>
<div class="et_pb_post">Some content with bg-color C</div>
<div class="et_pb_post">Some content with bg-color D</div>

答案 2 :(得分:1)

您可以从dom中获得一组元素,每个div都可以像这样:

print(welcome()):

然后,您可以循环遍历并使用与bg颜色数组中的index相同的循环计数器将属性分配给每个div元素...

function main() {  
  var sprsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = sprsheet.getActiveSheet();

  var data = {
    currentlblstr:sheet.getRange("A2:A6").getValues(),//In case you have more than A6, B6, etc, change the range to "A2:A", "B2:B", etc
    newlblstr:sheet.getRange("B2:B6").getValues(),
    email:sheet.getRange("C2:C6").getValues(),
    fromaddr:sheet.getRange("D2:D6").getValues(), //Since you are using appscript, the mails will be sent from the google user you are logged in
    shortname:sheet.getRange("E2:E6").getValues(), //I'm not sure what the shortname is for
    filename:sheet.getRange("F2:F6").getValues()
  };


  if (!CheckNulls(data)){
    for (var i in data.currentlblstr){
      var threads = findThreads(data.currentlblstr[i]);

      var body = threads[0].getMessages()[0].getBody();
      var attachment = threads[0].getMessages()[0].getAttachments();
      var label = threads[0].getLabels()[0].getName();
      var fileName = attachment[0].getName();

      threads[0].getMessages()[0].forward(data.email[i], {
                                      subject: data.shortname[i] + " " + subject,
                                      attachments: file});

      //Remove the label from the current thread
      var rem_label = GmailApp.getUserLabelByName(label);
      rem_label.removeFromThread(threads[0]);

      // GmailApp.sendEmail(data.email[i], subject, body);

    }
  }   
}

function CheckNulls(data){ // Returns true if there is any empty cell
  for (var key in data){

    for (var i in data[key]){

      if(!data[key][i][0]){
        return true;
      } 
    }
  }
}

function findThreads(labels){
   var threads = GmailApp.search("label:"+ labels); 
   return threads; //Returns an object GmailThread [1] 

}

关键是使用单个循环和索引在两个数组,div和颜色之间进行协调。

答案 3 :(得分:1)

您可以从颜色数组中删除所选颜色,因此无法再次选择它。作为奖励,我为您删除了jQuery。

// define colors
let colors = ["#CFEAEA", "#c9e3d5", "#e7dadd", "#dde9eb", "#ecfac7", "#facba9", "#dfdbd3", "#f1fdc1"];

// get all .et_pb_post elements and loop over 'em
document.querySelectorAll('.et_pb_post')
  .forEach((post) => {
    // get random color
    const randomColor = colors[Math.floor(Math.random() * colors.length)];

    // set background color for current post
    post.style.backgroundColor = randomColor;

    // filter colors to remove randomColor from the array
    colors = colors.filter((color) => color !== randomColor);
  });

答案 4 :(得分:0)

jQuery(document).ready(function($) {
var index = 0;
$(".et_pb_post").each(function(item) {
  var colors = ["#CFEAEA ","#c9e3d5","#e7dadd","#dde9eb","#ecfac7","#facba9","#dfdbd3","#f1fdc1"];
  var colorsLength = colors.length;
  var colorIndex = index%colorsLength;   
    $(this).css("background-color", colors[colorIndex]);
    index++;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="et_pb_post">Some content with bg-color A</div>
<div class="et_pb_post">Some content with bg-color B</div>
<div class="et_pb_post">Some content with bg-color C</div>
<div class="et_pb_post">Some content with bg-color D</div>