我有一個如下的html結(jié)構(gòu)
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
我如何應(yīng)用樣式,像前2個項目的一種風(fēng)格和后續(xù)2另一種風(fēng)格?第四個div之后的兩個div將會有和前兩個一樣的樣式,并且樣式會繼續(xù)。
正如@Chris G所建議的,您可以使用:n-child(4n+k)選擇器:
div:nth-child(4n + 1), div:nth-child(4n + 2) {
color: green;
}
div:nth-child(4n + 3), div:nth-child(4n) {
color: red;
}
<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>
<div>E</div>
<div>F</div>
<div>G</div>
<div>H</div>
<div>I</div>
<div>J</div>
這將解決實(shí)現(xiàn)你的目的....但效率不高
const divs = [...document.querySelectorAll('div')]
divs.forEach((el, i) => {
if (i % 3 == 0 || i % 3 == 1 || i % 3 == 2 ) el.style.backgroundColor = 'red'
if (i % 4 == 2 || i % 4 == 3) el.style.backgroundColor = 'blue'
})
如果我沒理解錯的話,它應(yīng)該是這樣的:
/* style 1 */
.rows > *:nth-child(4n+1),
.rows > *:nth-child(4n+2){
color: red;
}
/* style 2*/
.rows > *:nth-child(4n+3),
.rows > *:nth-child(4n+4){
color: blue;
}
<div class="rows">
<div>1: style 1</div>
<div>2: style 1</div>
<div>3: style 2</div>
<div>4: style 2</div>
<div>5: style 1</div>
<div>6: style 1</div>
<div>7: style 2</div>
<div>8: style 2</div>
</div>