Javascript:获取<div>的背景图片网址

cel*_*997 60 javascript css

如何在JavaScript中获取元素的background-imageURL <div>?例如,我有这个:

<div style="background-image:url('http://www.example.com/img.png');">...</div>
Run Code Online (Sandbox Code Playgroud)

我怎么会得到公正的网址background-image

pal*_*aѕн 78

你可以试试这个:

var img = document.getElementById('your_div_id'),
style = img.currentStyle || window.getComputedStyle(img, false),
bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
Run Code Online (Sandbox Code Playgroud)

// Get the image id, style and the url from it
var img = document.getElementById('testdiv'),
  style = img.currentStyle || window.getComputedStyle(img, false),
  bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");

// Display the url to the user
console.log('Image URL: ' + bi);
Run Code Online (Sandbox Code Playgroud)
<div id="testdiv" style="background-image:url('http://placehold.it/200x200');"></div>
Run Code Online (Sandbox Code Playgroud)

编辑:

根据@Miguel和下面的其他评论,如果您的浏览器(IE/FF/Chrome ...)将其添加到网址,您可以尝试删除其他引号:

bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
Run Code Online (Sandbox Code Playgroud)

如果它可能包括单引号,请使用: replace(/['"]/g, "")

DEMO FIDDLE

  • 不幸的是,这不适用于IE,因为返回的字符串被引用.所以我最终得到了这个:`bi = style.backgroundImage.slice(4,-1).replace(/"/ g,"");`现在有效:) (3认同)
  • `style.backgroundImage.slice(5, -2)` 当然也可以。 (2认同)
  • 这很棒,回答了 OP 9 年前的问题,但请注意,如果“backgroundImage”具有“线性渐变”,它将不起作用;例如:`背景图像:线性渐变(rgba(0, 0, 255, 0.5), rgba(255, 255, 0, 0.5)), url(https://my.image.com);` (2认同)

saw*_*yer 16

只是为了增加这个以防其他人有类似的想法,你也可以使用正则表达式:

var url = backgroundImage.match(/url\(["']?([^"']*)["']?\)/)[1];
Run Code Online (Sandbox Code Playgroud)

然而,根据jsPerf的说法,@ Praveen的解决方案似乎在Safari和Firefox中表现得更好:http://jsperf.com/match-vs-slice-and-replace

如果您想考虑值包含引号但不确定是双引号还是单引号的情况,您可以执行以下操作:

var url = backgroundImage.slice(4, -1).replace(/["']/g, "");
Run Code Online (Sandbox Code Playgroud)


Pra*_*man 6

试试这个:

var url = document.getElementById("divID").style.backgroundImage;
alert(url.substring(4, url.length-1));
Run Code Online (Sandbox Code Playgroud)

或者,使用 replace

url.replace('url(','').replace(')','');
// Or...
backgroundImage.slice(4, -1).replace(/["']/g, "");
Run Code Online (Sandbox Code Playgroud)

  • @narthur157 同意并更新了,但这是一个 7 年前的答案。 (3认同)

Ala*_*ust 6

首先,您需要返回背景图片内容:

var img = $('#your_div_id').css('background-image');
Run Code Online (Sandbox Code Playgroud)

这将返回如下URL:

“网址(' http://www.example.com/img.png ')”

然后,您需要删除此URL不需要的部分:

img = img.replace(/(url\(|\)|")/g, '');
Run Code Online (Sandbox Code Playgroud)