CSS循环样式 [英] Style for loop with CSS
问题描述
我应该制作8个框并为每个框设置样式,使框具有for循环.每个奇怪的盒子看上去都应该与其他盒子不同.我试图做一个id,但是当我在CSS中使用id时,它什么也不会做.有人可以帮忙吗?
Im supposed to make 8 boxes and style them each, make the boxes with for loop. Every odd box should look different then the others. I have tried to make an id, but when i use the id in CSS, it wont do anything. Can someone help?
这是我的代码:
var text = "";
var i;
for (i = 1; i < 10; i++) {
text += "Box number " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
.demo {
border: black;
}
<p id="demo"></p>
推荐答案
如volodymyr所说,请使用 css
nth-child属性.
As volodymyr says use css
nth-child property.
在javascript中,您可以通过以下方式完成此操作:
In javascript you can accomplish this in the following manner:
for(let i = 0; i < document.querySelectorAll('.class').length; i += 2){
document.querySelectorAll('.class')[i].style.color = 'red';
}
<div class="class">1</div>
<div class="class">2</div>
<div class="class">3</div>
<div class="class">4</div>
<div class="class">5</div>
<div class="class">6</div>
<div class="class">7</div>
<div class="class">8</div>
<div class="class">9</div>
<div class="class">10</div>
这使用了一个for循环,该循环遍历每个奇数元素,然后通过javascript应用样式.通常,通常最好使用纯CSS实现.
This uses a for loop which iterates over every odd element, and then applies styles via javascript. Usually a pure CSS implementation would be preferable though.
这篇关于CSS循环样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!