Вопрос

I have a HTML table. Some of the cells have #D6FFAD/rgb(214, 255, 173) as their background. I need to create a function that loops through the table and changes only cells with that background, to a different color. The interval needs to be consistent. It needs to go through the table cells in a particular order. This order is shown by their IDs (t1 - t10).

The below loops through and changes colours as needed. The consistency of the intervals is a problem though. For example, #T1 - #T4 all need their backgrounds changing, the interval is fine until here. There is then a delay whilst it looks at #T5 and #T6 before changing the color of #T7. I really need to skip 5 and 6 but struggling to think of a solution.

Can I put an IF statement for the second parameter of the setInterval()? Perhaps something like IF no background, set interval to 0 otherwise, 300?

CSS:

.changeThisBackgroundWithIntervalFunction{background:#D6FFAD}

JS:

i=1; 
setInterval(

function(){
t = document.getElementById('t'+i);
ts = window.getComputedStyle(t);
        if(ts.backgroundColor=='rgb(214, 255, 173)'){t.style.backgroundColor = 'pink';}
        i=i+1;

    if(i>=25){
        i=1;
        x = $("#selectDropdown option:selected").val();
        $('.'+x).css("background","#D6FFAD");
              }
       }    

 ,300);

HTML

<tr id="rowOne">
<td id="t1" class="changeThisBackgroundWithIntervalFunction">blah</td>  
<td id="t3" class="changeThisBackgroundWithIntervalFunction">blah</td>
<td id="t5">blah</td>
<td id="t7" class="changeThisBackgroundWithIntervalFunction">blah</td>
<td id="t9">blah</td>
<td id="t10" class="changeThisBackgroundWithIntervalFunction">blah</td>
</tr>

<tr id="rowTwo">
<td id="t2" class="changeThisBackgroundWithIntervalFunction">blah</td>  
<td id="t4" class="changeThisBackgroundWithIntervalFunction">Blah</td>
<td id="t6">Blah</td>
<td id="t8">blah</td>
<td id="t10" class="changeThisBackgroundWithIntervalFunction">Blah</td>
<td id="t12">Blah</td>
</tr>
Это было полезно?

Решение

You could first define which elements that need to be updated, put them in an array and then after each timeout, update the next element in that array.

var i;

var cellsToUpdate = [];
for(i = 1; i <= 12; i++) {
    var element = document.getElementById('t' + i);
    if (window.getComputedStyle(element).backgroundColor == 'rgb(214, 255, 173)')
        cellsToUpdate.push(element);
}

i = 0;
var interval = setInterval(
function () {
    if (i >= cellsToUpdate.length) {
        clearInterval(interval);
        return;
    }
    cellsToUpdate[i].style.backgroundColor = 'pink';
    i++;
}

, 300);

Check out this fiddle. Call the code above after you have changed the colors with the select dropdown. Don't forget to clear the interval when it is done.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top