使用javascript从分区获取背景图像的url
我在一个网站中有一个元素如下:使用javascript从分区获取背景图像的url,javascript,html,css,Javascript,Html,Css,我在一个网站中有一个元素如下: <div id="item" style="background-image: url('url to the image')"></div> var item = document.getElementById('item'); var newStyle = 'background-image: url(' + yourVar + ');'; item.setAttribute('style', newStyle); 现在我需要一
<div id="item" style="background-image: url('url to the image')"></div>
var item = document.getElementById('item');
var newStyle = 'background-image: url(' + yourVar + ');';
item.setAttribute('style', newStyle);
现在我需要一个javascript,它只提取这个背景图像的url,并用存储在var中的url替换它
如何以“整洁”的方式实现这一点:)?您可以通过其
id
选择div,并使用setAttribute
将style
属性设置为包含存储在yourVar
中的新url的字符串,如下所示:
<div id="item" style="background-image: url('url to the image')"></div>
var item = document.getElementById('item');
var newStyle = 'background-image: url(' + yourVar + ');';
item.setAttribute('style', newStyle);
OP没有说他们正在使用jQuery。有点期待他们包括整个图书馆只是为了这个…@Leetylor我不会说这是太多的期望。jQuery与其他类似的库一起非常常见,但应该公开的是,这需要jQuery。