I have a loop that creates a new div for each unique event
while($event!=$nextEvent){
echo'<div id='sportType'>';
//some code
echo'</div>'
}
I would like to automatically change the background-colour to a different background-colour for each created div, each div must be a separate/unique colour, there will never be more than 7 divs
Something like this
Any idea how I can do this?
Since there is at most 7 divs, you can do this with pure css and the nth-child selector
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;
}
If you desire more than seven divs, it will be more practical with javascript like
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>
You can do it in PHP itself as follows
Declare an array which contains the colour codes and use the array when you create the <div>
s dynamically.See the below code as an example
<?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++;
}
?>
You can just specify any number of colours in the array and it will apply the colours accordingly even if a large number of <div>
is created,ie for eg if you want 100 divs to be created, you can just add 100 or more than 100 colour codes in your array and these colours will be used in the while loop.
you can use the function rand
to generate new colors
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
function will creat a random number to the RGB color collection.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.