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

IT技术 javascript css
2021-01-19 03:23:45

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

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

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

6个回答

你可以试试这个:

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, "")

演示小提琴

片??我觉得自己像个中世纪的农民
2021-03-15 03:23:45
Firefox 也引用了字符串。至少从 FF39 开始。
2021-03-19 03:23:45
这很好,并且在 9 年前回答了 OP 的问题,但请注意,如果backgroundImagelinear-gradient; 例如:background-image: linear-gradient(rgba(0, 0, 255, 0.5), rgba(255, 255, 0, 0.5)), url(https://my.image.com);
2021-03-20 03:23:45
style.backgroundImage.slice(5, -2) 当然也有效。
2021-04-03 03:23:45
不幸的是,这在 IE 上不起作用,因为返回的字符串是引用的。所以我最终得到了这个:bi = style.backgroundImage.slice(4, -1).replace(/"/g, ""); 现在可以工作了:)
2021-04-05 03:23:45

只是为了以防万一其他人有类似的想法,您也可以使用正则表达式:

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

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

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

var url = backgroundImage.slice(4, -1).replace(/["']/g, "");
这是完整的答案
2021-03-13 03:23:45
|是不需要的在你的正则表达式,该[...]装置的任何字符之内。replace(/["']/g, "")没问题
2021-03-29 03:23:45

试试这个:

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, "");
@narthur157 同意并更新,但这是一个 7 年前的答案。😅
2021-03-14 03:23:45
这个子字符串只是删除了url(. 它不会删除引号。替换不适用于双引号。使用子字符串替换是可以的,但不会处理双引号。backgroundImage.slice(4, -1).replace(/["']/g, "");是你要找的
2021-03-26 03:23:45

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

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

这将返回如下 URL:

"url(' http://www.example.com/img.png ')"

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

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

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}`);
    });
}