【问题标题】:Change Background Image in a loop循环更改背景图像
【发布时间】:2016-10-12 01:11:31
【问题描述】:

对我来说,这似乎是一个简单的想法——当您单击一个 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;
}

【问题讨论】:

    标签: javascript html css image background-image


    【解决方案1】:

    你还需要url("..."):

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

    【讨论】:

      【解决方案2】:

      CSS background-image 属性要求 URL 包含在 'url(...)' 中:

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

      【讨论】:

        猜你喜欢
        • 2014-07-29
        • 1970-01-01
        • 2016-01-09
        • 2020-12-16
        • 2011-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多