Apply style to first element in a row of similar e

2019-01-20 05:57发布

问题:

I have the following list (the numbers are just for reference)

<div class="A">alpha1</div>
<div class="B">alpha2</div>
<div class="A">alpha3</div>
<div class="A">alpha4</div>
<div class="A">alpha5</div>
<div class="B">alpha6</div>
<div class="A">alpha7</div>

I want to apply one style to DIVS 1, 3 and 7, because they are the first of their class (A) in a row of elements of the same class. Is there a pseudo element / magic I can use for that? Something like (inventing)

not(.A) & .A {color:red} -> if class is A and it is not preceded by an A

Thanks!

回答1:

You use the :not() pseudo-class with an adjacent sibling combinator + to match an .A that is not immediately preceded by an .A:

:not(.A) + .A

You'll also need to use :first-child to select the very first .A element since it's not preceded by anything:

.A:first-child

Combine them, and you have:

:not(.A) + .A, .A:first-child { color: red; }

jsFiddle demo



回答2:

Here is a cross browser solution using JavaScript:

http://jsfiddle.net/YhvGw/

function applyStyleToFirstDiv(className, styleAttr, val,baseSelector) {
    //Allow to specify a base element to search in
    if(baseSelector == null){
        baseSelector = document    
    }
    var divElements = baseSelector.getElementsByTagName("div"),
        len = divElements.length;
    var prevWas = false,currentIs;
    // Go through all the divs
    for (var i = 0; i < len; i++) {
        var cur = divElements[i];
        var classes = cur.className.split(" ");
        currentIs = false;
        for (var j = 0; j < classes.length; j++) {
            //If you find a matching class
            if (classes[j] === className) {
                currentIs = true;
                break;
            }
        }
        //If the current one matches, and the last one didn't, apply the style, otherwise don't
        if(currentIs && !prevWas){
            cur.style[styleAttr] = val;    
        }
        prevWas = currentIs;

    }
}
//usage sample
applyStyleToFirstDiv("A","color","yellow");


回答3:

Here is an example:

div:not(.A) + .A, .A:first-of-type{
color:red;
}