如何使用JavaScript获取元素的背景图片网址?


74

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

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

我如何获取URL background-image

Answers:


93

您可以尝试以下方法:

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

编辑:

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

bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");

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

演示场


3
不幸的是,这在IE上不起作用,因为返回的字符串用引号引起来。所以我最终得到了这一点:bi = style.backgroundImage.slice(4, -1).replace(/"/g, ""); 现在可以工作了:)
Miguel Garrido

1
Firefox也引用字符串。至少从FF39​​开始。
2015年

1
style.backgroundImage.slice(5, -2)当然也可以。
马克·休伊特

片??我感觉像个中世纪的农民
工具包

20

只是在万一其他人有类似想法的情况下添加此内容,您也可以使用Regex:

var url = backgroundImage.match(/url\(["']?([^"']*)["']?\)/)[1];

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

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

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

1
这是完整的答案
Mladen Janjetovic

1
|是不需要的在你的正则表达式,该[...]装置的任何字符之内。replace(/["']/g, "")没关系
S.Serpooshan

8

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

var img = $('#your_div_id').css('background-image');

这将返回如下URL:

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

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

img = img.replace(/(url\(|\)|")/g, '');

8

尝试这个:

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

或者,使用replace

url.replace('url(','').replace(')','');
// Or...
backgroundImage.slice(4, -1).replace(/["']/g, "");

1
此子字符串仅删除url(。它不会删除引号。替换不适用于双引号。可以使用子字符串替换,但是不能处理双引号。backgroundImage.slice(4, -1).replace(/["']/g, "");是您正在寻找的东西
narthur157 '19

1
@ narthur157同意并更新,但这是7年的答案。😅
普利文库马尔Purushothaman

1

const regex = /background-image:url\(["']?([^"']*)["']?\)/gm;
const str = `<div style="background-image:url('http://www.example.com/img.png');">...</div>`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}


0

登录控制台所有background-imageURL,不带括号和引号:

var element = document.getElementById('divId');
var prop = window.getComputedStyle(element).getPropertyValue('background-image');
var re = /url\((['"])?(.*?)\1\)/gi;
var matches;
while ((matches = re.exec(prop)) !== null) {
    console.log(matches[2]);
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.