Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript从分区获取背景图像的url_Javascript_Html_Css - Fatal编程技术网

使用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。