2014-12-17 4 views
2

У меня есть матрица 5x5 div с начальным цветом brown.On каждого обновления он должен сделать 7 случайных цветов, как код ниже. Мой вопрос, как я могу сделать это так на каждом обновлении он помещает 4 из каждый 6 разных цветов в функции наведения и 7-й цвет в последнем свободном div?
полного код здесь->http://pastebin.com/tUxB5usi
Цвет JQuery на hover randomize

<script> 
     $(document).ready(function() { 
      var b = 15; 
      var Otv = "Отворени: "; 
      var c = 3; 
      var Prom = "Промени: "; 
      document.getElementById('otvoreni').innerHTML = Otv + b; 
      document.getElementById('promeni').innerHTML = Prom + c; 
      var f="#B"+Math.floor(Math.random() * 99999); 
      var f1="#B"+Math.floor(Math.random() * 99999); 
      var f2="#B"+Math.floor(Math.random() * 99999); 
      var f3="#B"+Math.floor(Math.random() * 99999); 
      var f4="#B"+Math.floor(Math.random() * 99999); 
      var f5="#B"+Math.floor(Math.random() * 99999); 
      var f6="#B"+Math.floor(Math.random() * 99999); 
      $(".inner").hover(function() { 
       if (b > 0) { 
        $(this).css("background-color", f); 
        b--; 
        document.getElementById('otvoreni').innerHTML = Otv + b; 
       }; 
      }, function() { 
       $(this).css("background-color", "#B87333"); 
      }); 

     }); 
    </script> 
+1

Создайте случайный индекс (случайный * 6) и сохраните его в переменной. Используйте этот индекс в своем div и запустите цикл, исключая значение массива, соответствующее этому индексу (используя if). – Playmaker

+0

. Я забыл упомянуть, что даже места, в которых размещены 7 цветов, должны быть рандомизированы. О рандомизации размещения цвета i получил этот тивм. –

+0

Можете ли вы прояснить, сколько ящиков вам нужно для присвоения цвета? Сначала вы упоминаете матрицу 5x5, поэтому я предполагаю, что у вас есть 25 div, а позже вы говорите «7-й цвет в последнем свободном div», что означает, что у вас есть 7 divs. – Chop

ответ

2

принимая @Chop решения, я сделал последний квадрат, чтобы сделать не быть таким же всегда.

$(document).ready(function() { 
    var b = 15; 
    var Otv = "Отворени: "; 
    var c = 3; 
    var Prom = "Промени: "; 
    document.getElementById('otvoreni').innerHTML = Otv + b; 
    document.getElementById('promeni').innerHTML = Prom + c; 
    var colors = {1:["red",4],2:["blue",4],3:["green",4],4:["gray",4],5:["orange",4],6:["purple",4],7:["black",0]} 

    function selectColor(index){ 
     var noColor=true; 
     while(noColor){ 
      if(colors[index][1]>0){ 
       colors[index][1]=colors[index][1]-1; 
       noColor=false; 
       return index; 
      }else{ 
       index = Math.ceil(Math.random() * 6); 
      } 
     } 
    } 

    function setEventHandlers(element, index){ 
     element.on("mouseenter",function(e){ 
      var color = colors[index][0]; 
      $(this).css("background-color", color); 
     }); 
     // element.on("mouseleave",function(e){ 
      // $(this).css("background-color", "#B87333"); 
     // }); 
    } 

    var winner = Math.floor(Math.random()*24); 
    var elements = $(".inner"); 
    for(var y = 0; y < elements.length; y++){ 
     var element = elements.eq(y) 
     if(y == winner) setEventHandlers(element,7) 
     else setEventHandlers(element, selectColor(Math.ceil(Math.random() * 6))) 
    } 
}); 
1

Вы мог бы сделать это таким образом

var colors = [] 
for(var x = 0; x < 7; x++){ 
    //Fill the array with random colors 
    colors.push("#B"+Math.floor(Math.random() * 99999)) 
} 

//Remove the last color and store it in a separate variable 
var lastColor = colors.splice(colors.length - 1, 1) 

//Function for array shuffling 
function shuffle(o){ 
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); 
    return o; 
}; 

function setEventHandlers(element, index, last){ 
    //If this is the last element, then use the 7th color, otherwise pick the color at index 
    if (last) var color = lastColor 
    else var color = colors[index] 

    //Set up the event handlers with the chosen color 
    element.on("mouseenter",function(e){ 
     $(this).css("background-color", color); 
    }) 
    element.on("mouseleave",function(e){ 
     $(this).css("background-color", "#B87333"); 
    }) 
} 

//Store all elements with class inner in the variable elements 
var elements = $(".inner") 

//Loop through the elements array 
for(var y = 0; y < elements.length; y++){ 
    var element = elements.eq(y) 

    //If the loop has gone once through all colors, shuffle the colors array 
    if(y % 6 == 0) colors = shuffle(colors) 

    //If the index equals 24, that means we are at the last element, we call the setEventHandlers with attribute index = 0 (won't be used anyways) and last set to true 
    if(y == 24) setEventHandlers(element, 0, true) 

    //If not the last square, then call setEventHandlers for the current element with index = current index modulo 6 (# of colors), which will always be an integer in the [0,5] range 
    else setEventHandlers(element, y % 6, false) 
} 
+0

Размещение цвета в div должно быть в рандомизированном месте, не в диагональном шаблоне. –

+0

Обновлено мое сообщение, чтобы рандомизировать назначение цвета – Chop

+0

Теперь это лучше, но есть одна последняя вещь, каждый из 6 цветов должен быть помещен всего 4 раза, а оставшийся на оставшийся div. В вашем коде один цвет появляется более 4 раз. Как я сказал 6 (разные цвета) x4 (каждого цвета) = 24 divs и последний оставшийся цвет для последнего оставшегося свободного div. –

Смежные вопросы