为每个DOM元素应用随机CSS

时间:2014-11-20 09:04:04

标签: javascript jquery html css

我试图这样做,以便每次页面加载时,我的所有卡片都会被删除。是不同的颜色。我有一个'随机发生器'随机化对象,然后一旦运行,我尝试应用于我的HTML元素。它似乎无法正常工作,但我在缩小范围时遇到了一些麻烦。

    <script>
    document.addEventListener("DOMContentLoaded", function() {
    cardColors =  [{ top: '#68B78F', bottom: '#4CAF7C' }, 
                { top: '#9BC0CD', bottom: '#79B1C4' }, 
                { top: '#CDCA00', bottom: '#E7B700' },
                { top: '#C3322B', bottom: '#AF2B26' }];

    var cards = document.getElementsByClassName('card');
    for (var i = 0; i < cards.length; i++) {
      var color = cardColors.shuffle();
      console.log($(cards[0]));
      $(cards[i]).css('background-color', color[0].top);      
      $(cards[i]).css('background-color', color[0].bottom);  
    };
  });  

  Array.prototype.shuffle = function() {
    var input = this;
    for (var i = input.length-1; i >=0; i--) {
      var randomIndex = Math.floor(Math.random()*(i+1)); 
      var itemAtIndex = input[randomIndex];    
      input[randomIndex] = input[i]; 
      input[i] = itemAtIndex;
    }
    return input;
  };
    </script>

最终,我试图通过Django模板显示它:

<div class="cards">
  {% for book in books %}
    {% for passage in highlighted %}
    <div class="card">
      <div></div>
      <p>{{book.title |safe }}</p>
      <p>{{book.author |safe }}</p>
      <p>{{passage |safe }}</p>
    </div>
    {% endfor %}
  {% endfor %}
</div>

除了帮助之外,还希望听到一些重构建议!

2 个答案:

答案 0 :(得分:0)

这里我对你的代码进行了一些改进。

 document.addEventListener("DOMContentLoaded", function() {
    cardColors =  [{ top: '#68B78F', bottom: '#4CAF7C' }, 
            { top: '#9BC0CD', bottom: '#79B1C4' }, 
            { top: '#CDCA00', bottom: '#E7B700' },
            { top: '#C3322B', bottom: '#AF2B26' }];

    var cards = document.getElementsByClassName('card');
    var color = cardColors.shuffle();
    for (var i = 0; i < cards.length; i++) {
        current_color = color.pop();
        $(cards[i]).css('background-color', current_color.top);      
        $(cards[i]).css('background-color', current_color.bottom);  
    };
  });  

  Array.prototype.shuffle = function() {
    var input = this;
    for (var i = input.length-1; i >=0; i--) {
      var randomIndex = Math.floor(Math.random()*(i+1)); 
      var itemAtIndex = input[randomIndex];    
      input[randomIndex] = input[i]; 
      input[i] = itemAtIndex;
    }
    return input;
  };

这是演示...... http://jsfiddle.net/u309pgjm/1/

答案 1 :(得分:0)

我宁愿选择更随机的方法,每次都会显示独特的颜色,直到每种颜色至少显示一次。
我的方法是基于存储到目前为止尚未显示的卡片颜色并随机选择其中一种。因此,它不会重复颜色,直到每种颜色至少使用一次。 以下是使用localStorage的方法:

var cardColors = [{id : 1,top : '#68B78F',bottom : '#4CAF7C'}];//id added to ease the comparison
var cardColor, usedCardColors = JSON.parse(localStorage.getItem("usedCardColors "));
if(usedCardColors === null) {
    usedCardColors = [];
}
var unUsedCardColors = difference(usedCardColors, cardColors, 'id');//id is the property to be compared
if(unUsedCardColors.length === 0) { //All cardColors  used at once
    //you may wish to restart all over by removing  localStorage usedCardColors
} else {
    cardColor = unUsedCardColors[Math.floor(Math.random() * unUsedCardColors.length)];
    localStorage.setItem("usedCardColors ", JSON.stringify(usedCardColors.push(cardColor)));
    applyColorToElements(cardColor); //loop to Elements to set color
}

function difference(a, b, pk) { //b -a //fn can be compacted by using array filter/map etc
    var c = [],found;
    for(var i = 0; i < b.length; i++) {
        found = false;
        for(var j = 0; j < a.length; j++) {
            if(a[j][pk] === b[i][pk]) {
                found = true;
                break;
            }
        }
        if(!found) {
            c.push(b[i]);
        }
    }
    return c;
}