Alternate <tr> background color, even if <tr> is not displayed

How to add a background color to every second row of the table, even some rows of the table are not displayed?

In my HTML, a simple table with some table rows. Similar:

<label for="cb">hide blue</label>
<input id="cb" type="checkbox" onchange="hideBlue(this.checked)" />

<table>
    <tr data-cat="red">
        <td>red car</td>
    </tr>
    <tr data-cat="blue">
        <td>blue jacket</td>
    </tr>
    <tr data-cat="red">
        <td>red bull</td>
    </tr>
    <tr data-cat="red">
        <td>red pen</td>
    </tr>
</table>

As you can see, there is also a checkbox that can toggle the blue line categories. My CSS looks like this:

tr:nth-child(odd) {
    background-color:#aaa;
}

But now, if someone hides the “blue” category (adding a display:none-class), the background colors no longer alternate. How can I prevent this failure?

I already tried to add :not(.displaynone)css to the rule, but that didn't work.

Here is jsFiddle

+4
source share
3 answers

CSS.

tr:nth-child(odd) {
    background-color:#aaa;
}

tr.displaynone ~ tr {
    background-color: transparent;
}

tr.displaynone ~ tr:nth-child(even) {
    background-color:#aaa;
}

, displaynone background-color transparent, background-color #aaa.

(forked here), , . (, ).

, , javascript , / .

+2

jQuery, ( , ).

function loopTable() {
    var x=0;
    $("table>tbody>tr").each(function() {
        if( $(this).is(":visible")  ) {
            if( x%2==0 )
                $(this).addClass('red');
            else
                $(this).removeClass('red');
            x++;     
        }
    });
}

, , . .

DEMO.

0

According to your requirement, only jQuery can solve your problem. Even one <tr>is hidden, the background color will be in sequence. Check out DEMO .

Here is the jQuery code.

$(document).ready(function(){

$("tr[data-cat='red']:even").css({'background':'red'});
$("tr[data-cat='red']:odd").css({'background':'orange'});
$("tr:not([data-cat='red'])").css({'background':'blue'});
});
0
source

All Articles