2016-06-11 114 views
1

對我來說,這看起來像一個簡單的想法 - 當您單擊一個div時,該div的背景圖像會發生變化。到目前爲止,我已經嘗試了這種顏色(將顏色名稱放在數組中,將「box.style.backgroundImage」更改爲「box.style.backgroundColor」) 它可以很好地處理顏色,但不適用於圖像。任何想法爲什麼?在循環中更改背景圖像

的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; 
} 

回答

5

你仍然需要url("...")

box.style.backgroundImage = 'url("' + img + '")'; 
2

的CSS 背景圖像屬性需要的URL 'URL(...)' 括起來:

box.style.backgroundImage = 'url(' + img + ')';