选择第n个兄弟节点 [英] Select the nth following sibling
问题描述
我想知道是否有一个更好的解决方案比我发现没有改变html结构
I wondered if there is a better solution than to what I found without changing the html-structure
HTML结构看起来像这样
The HTML structure looks like this
<div class="wrap">
<div class="divider"></div>
<div class="block"></div>
<div class="block"></div>
<div class="divider"></div>
</div>
所以在同一级别上有各种DIV,我想做的是
So there's various DIVs on the same level, what I want to do is to color every fourth block differently, until a divider appears, then it'd have to recount.
我认为像 .block:nth-child(4n)
会做的伎俩,但它实际上计数的基于父,而不是基于类的元素。
I thought something like .block:nth-child(4n)
would do the trick, but it actually counts the elements based on the parent, not based on the class.
这里是JSFiddle试试。
每行块#4和#8应该有不同的颜色
http:// jsfiddle .net / SKgdH / 3 /
Here's the JSFiddle to try out. Block #4 and #8 in each row should be differently colored http://jsfiddle.net/SKgdH/3/
这就是我的工作方式:
http://jsfiddle.net/SKgdH/1/
And this is how I made it sort-of work: http://jsfiddle.net/SKgdH/1/
我做了什么是寻找像 .divider + .block + .block + .block + .block
它的工作原理,但是,我必须写同样的第8,第12,第16,..块,这不会使它自动了。
It works, however, I'd have to write the same for the 8th, 12th, 16th, .. block, which doesn't make it automatic anymore.
有 .divider + .block:nth-sibling(4)
或 .divider + .block:nth-of-类(4)
?
也许你们中的一个想到了如何解决这个问题而不改变源代码或使用javascript。 p>
Maybe one of you got an idea on how to solve this without changing the source code or using javascript.
推荐答案
这样的伪类不会工作,因为你期望它匹配元素相对于不同的复合选择器,这不是如何简单的选择器工作。例如,如果你写了一个复杂的选择器,只有一个复合选择器与伪类(没有兄弟的组合器):
Such a pseudo-class would not work because you are expecting it to match elements relative to a different compound selector, which is not how simple selectors work. For example, if you wrote a complex selector that only had a single compound selector with that pseudo-class (and no sibling combinators):
.block:nth-sibling(4n)
您期望这匹配 .block:nth-child(4n)
,什么都不匹配或无效?
Would you expect this to match .block:nth-child(4n)
, match nothing at all, or be invalid?
能够擦除 + .block + .block + .block + .block
,并使它重复某种方式,但不幸的是由于选择器语法的设计,它是不可能的。
It'd be nice to be able to abridge + .block + .block + .block + .block
and make it repeat somehow, but unfortunately due to how the selector syntax is designed, it's just not possible.
您必须使用JavaScript和/或向适当的元素添加额外的类。
You'll have to use JavaScript and/or add extra classes to the appropriate elements instead.
这篇关于选择第n个兄弟节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!