Random images, 2 different divs [HTML,JavaScript]
so I need some help. I have a small iphone site and I want the bars (4 images) to random at the same color. (like a theme)
So like this
Barred1.jpg , Barred2.jpg , Barred3.jpg Barred4.jpg
Barblue1.jpg , Barblue2.jpg , Barblue3.jpg B开发者_StackOverflow中文版arblue4.jpg
Barpink1.jpg , Barpink.jpg , Barpink3.jpg Barpink4.jpg
Bargreen1.jpg , Bargreen2.jpg , Bargreen3.jpg Bargreen4.jpg
How do it?
All the bars are on different divs..
I'm sorry for my bad English.
You could have JavaScript choose a color at random (using this technique) and then work through all images on the page like this:
var imgs = document.getElementsByTagName('img'),
i = imgs.length;
while (i) {
i -= 1;
Then you could check the image's src
attribute like so:
if (/^Bar([a-z]+)\.jpg/.test(imgs[i].src)) {
If it matches, just switch out the src with the color your JS arrived at:
imgs[i].src = 'Bar' + random_color + '.jpg';
step 1 is to assign each color a number, then use random number to pick a color
var colors = new Array("red","blue","pink","green");
var random = Math.floor(Math.random()*4);
step 2 is to use a for loop to set the img src to the color
for (var i=1; i < 5; i++){
document.getElementById("img"+i).src = "Bar"+colors[random]+i+".jpg";
}
Using jquery:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
var a = ['red', 'blue', 'pink', 'green'];
function setBarTheme(bar, idx)
{
$(bar).css('background-image', 'url(Bar' + a[idx] + '.jpg)');
}
$(document).ready(function(){
var r = Math.floor(Math.random()*4);
setBarTheme('#bar1', r);
setBarTheme('#bar2', r);
setBarTheme('#bar3', r);
setBarTheme('#bar4', r);
});
</script>
</head>
<body>
<div id="bar1"></div>
<div id="bar2"></div>
<div id="bar3"></div>
<div id="bar4"></div>
</body>
</html>
精彩评论