使用javascript从div元素中获取background-image的url

时间:2014-05-09 16:46:32

标签: javascript html css

我在网站上有一个如下所示的元素:

<div id="item" style="background-image: url('url to the image')"></div>

现在我需要一个javascript,它只提取此背景图像的网址,并将其替换为存储在var中的网址。

这怎么可能在&#34;整洁&#34;方式:)?

2 个答案:

答案 0 :(得分:2)

您可以按id选择div,然后使用setAttributestyle属性设置为包含yourVar中存储的新网址的字符串,如下所示:

var item = document.getElementById('item');
var newStyle = 'background-image: url(' + yourVar + ');';
item.setAttribute('style', newStyle);

答案 1 :(得分:1)

$('#item').css('background-image', 'url(' + var + ')');