对我而言,这似乎是一个简单的想法 - 当你点击div时,该div的背景图像会发生变化。到目前为止,我已尝试使用颜色(将颜色名称放在数组中,更改" box.style.backgroundImage" to" 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;
}
答案 0 :(得分:4)
您仍然需要url("...")
:
box.style.backgroundImage = 'url("' + img + '")';
答案 1 :(得分:2)
CSS background-image 属性要求网址包含在&#39; url(...)&#39;中:
box.style.backgroundImage = 'url(' + img + ')';