[英]Change background-colour of div for each new div created
我有一个循环,为每个独特的事件创建一个新的div
while($event!=$nextEvent){
echo'<div id='sportType'>';
//some code
echo'</div>'
}
我想自动将背景颜色更改为每个创建的div的不同背景颜色, 每个div必须是单独/唯一的颜色,永远不会超过7个div
像这样的东西
知道我怎么能这样做吗?
由于最多有7个div,你可以使用纯css和nth-child选择器来完成
div:nth-child(1) {
background: gray;
}
div:nth-child(2) {
background: red;
}
div:nth-child(3) {
background: cyan;
}
div:nth-child(4) {
background: blue;
}
div:nth-child(5) {
background: black;
}
div:nth-child(6) {
background: green;
}
div:nth-child(7) {
background: yellow;
}
如果你想要七个以上的div,那么用javascript会更实用
var divs = document.getElementsByTagName('div'); for(var i =0; i < divs.length; i++){ divs[i].style.background = getRandomColor(); } function getRandomColor() { var letters = '0123456789ABCDEF'.split(''); var color = '#'; for (var i = 0; i < 6; i++ ) { color += letters[Math.floor(Math.random() * 16)]; } return color; }
<div>test</div> <div>test</div> <div>test</div> <div>test</div> <div>test</div> <div>test</div> <div>test</div> <div>test</div> <div>test</div> <div>test</div>
您可以在PHP本身中执行以下操作
声明一个包含颜色代码的数组,并在动态创建<div>
时使用该数组。请参阅下面的代码作为示例
<?php $color= array("#341014", "#BE6353", "#2F2E3B","#20222B","#BB644C","#F8834E","#E4B9AC");
$i=0;
while($event!=$nextEvent){
echo"<div id='sportType' style='background-color:".$color[i].";'>";
//some code
echo'</div>';
$i++;
}
?>
您可以在数组中指定任意数量的颜色,即使创建了大量的<div>
,它也会相应地应用颜色,例如,如果您想要创建100个div,则可以添加100或更多数组中有100个颜色代码,这些颜色将在while循环中使用。
您可以使用rand
函数生成新颜色
while($event!=$nextEvent){
$r=rand(0, 255);
$g=rand(0, 255);
$b=rand(0, 255);
echo"<div id=\"sportType\" style=\"backgroung:rgb($r,$g,$b);\">";
//some code
echo "</div>"
}
rand
函数将为RGB颜色集合创建一个随机数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.