samedi 11 juin 2016

Change Background Image in a loop


To me, this seems like a simple idea- when you click a div, the background image of that div changes. So far, I've tried this with colors (put color names in the array, change "box.style.backgroundImage" to "box.style.backgroundColor") It works fine with colors, but not with images. Any idea why?

Javascript:

var box = document.getElementById('box'),
imgs = ['/image.jpg', '/image2.jpg'];

box.onclick = function () {
img = imgs.shift();
imgs.push(img);

box.style.backgroundImage = img;
};

HTML:

<div id='box'></div>

CSS:

#box {
background: url("https://priteshgupta.com/wp-content/uploads/2011/06/html-ipsum.png");
width:200px;
height:200px;
margin:50px;
}

Aucun commentaire:

Enregistrer un commentaire