:nth-child(2n) of [attribute=value]

2019-06-22 05:30发布

问题:

I have a list with rows, each li has an attribute data-status which the value can be 1-5:

<ul>
    <li data-status="1"></li>
    <li data-status="2"></li>
    <li data-status="2"></li>
    <li data-status="1"></li>
    <li data-status="1"></li>
    <li data-status="2"></li>
    <li data-status="3"></li>
    <li data-status="4"></li>
    <li data-status="5"></li>
    <li data-status="5"></li>
    <li data-status="1"></li>
</ul>

I want each odd li that the data-status is 1 to be have a different background, is it possible to do in CSS?

回答1:

If the question is how to select all the odd elements with a particular attribute ?, then it is possible how explained in the other answers, with

li[data-status="1"]:nth-child(2n+1) {
   background: #f00;
}

or in an even easier way:

li[data-status="1"]:nth-child(odd) {
   background: #f00;
}

Take a look at this good article on how nth-child works.

If, instead, the question is how to select all the elements with a particular attribute, and then pick only the odd of that sub-list ? , well, that is not yet possible with CSS, but it will with CSS Selectors Level 4, as explained here, with the nth-match() pseudo-class:

:nth-match(An+B of <selector>)

that in your case would be

li:nth-match(2n+1 of [data-status="1"])

or

li:nth-match(odd of [data-status="1"])

Let's wait... CSS4 is coming !! :P


EDIT: as reported by Michael_B, this feature has been stripped by CSS4 specifications, so stop waiting and start figuring another way to do it :/



回答2:

I believe you can do

li[data-status="1"]:nth-child(odd) {
    background: #f90;
}

There's a working example at http://jsfiddle.net/adamh/ggtff/



回答3:

If you're not against using jQuery you can use this approach.

$('li[data-status=1]').toggleClass(function(idx){
  return idx % 2 === 0 ? 'odd-status-one' : 'even-status-one'; 
});

Here's a quick demo: http://jsbin.com/arawur/3/edit