我有以下列表(这些数字仅供参考)
<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>
我想将一种样式应用于DIVS 1,3和7,因为它们是同一类元素中的第一个类(A)。我可以使用伪元素/魔法吗?像(发明)
的东西not(.A) & .A {color:red} -> if class is A and it is not preceded by an A
谢谢!
答案 0 :(得分:4)
您将:not()
伪类与相邻的兄弟组合+
一起使用,以匹配.A
之前没有.A
的{{1}}:
:not(.A) + .A
您还需要使用:first-child
来选择第一个.A
元素,因为它之前没有任何内容:
.A:first-child
结合它们,你有:
:not(.A) + .A, .A:first-child { color: red; }
答案 1 :(得分:3)
以下是使用JavaScript的跨浏览器解决方案:
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");
答案 2 :(得分:1)
以下是一个例子:
div:not(.A) + .A, .A:first-of-type{
color:red;
}