我想知道是否有更好的解决方案,而不是改变html结构
HTML结构看起来像这样
<div class="wrap"> <div class="divider"></div> <div class="block"></div> <div class="block"></div> <div class="divider"></div> </div>因此,在同一级别上有各种DIV,我想要做的是以不同的方式对每个第四块进行着色,直到出现分隔线,然后再重新计算。
我认为像.block:nth-child(4n)这样的东西可以做到这一点,但它实际上是基于父类而不是基于类来计算元素。
这里是JSFiddle试用。 每行中的块#4和#8应该有不同的颜色http://jsfiddle.net/SKgdH/3/
这就是我如何做它的工作: http : //jsfiddle.net/SKgdH/1/
我所做的就是寻找.divider的第四个兄弟,像这样.divider + .block + .block + .block + .block
它可以工作,但是,我必须在第8,12,16,...块中写入相同的内容,但不会使其自动生效。
有没有像.divider + .block:nth-sibling(4)或.divider + .block:nth-of-class(4) ?
也许你们中的一个人在不改变源代码或使用javascript的情况下就知道如何解决这个问题。
I wondered if there is a better solution than to what I found without changing the html-structure
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>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.
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.
Here's the JSFiddle to try out. Block #4 and #8 in each row should be differently colored http://jsfiddle.net/SKgdH/3/
And this is how I made it sort-of work: http://jsfiddle.net/SKgdH/1/
What I did was to look for the 4th sibling of the .divider like this .divider + .block + .block + .block + .block
It works, however, I'd have to write the same for the 8th, 12th, 16th, .. block, which doesn't make it automatic anymore.
Is there something like .divider + .block:nth-sibling(4) or .divider + .block:nth-of-class(4)?
Maybe one of you got an idea on how to solve this without changing the source code or using javascript.
最满意答案
这样的伪类不会工作,因为您期望它匹配相对于不同复合选择器的元素,而不是简单的选择器的工作方式。 例如,如果你编写了一个复杂的选择器,只有一个具有该伪类的复合选择器(并且没有同级组合器):
.block:nth-sibling(4n)你会期望这匹配.block:nth-child(4n) ,完全没有匹配,或者无效?
能够缩小+ .block + .block + .block + .block并以某种方式重复它会很好,但不幸的是,由于选择器语法的设计方式,这是不可能的。
您必须使用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)Would you expect this to match .block:nth-child(4n), match nothing at all, or be invalid?
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.
You'll have to use JavaScript and/or add extra classes to the appropriate elements instead.
更多推荐
发布评论