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

mzaanser  于 2023-01-27  发布在  Java
关注(0)|答案(6)|浏览(179)

如何在JavaScript中获取<div>元素的background-image URL?例如,我有以下代码:

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

我如何得到background-image的URL?

jv4diomz

jv4diomz1#

你可以试试这个:

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

x一个一个一个一个x一个一个二个x

    • 编辑:**

基于@Miguel和下面的其他评论,如果您的浏览器(IE/FF/Chrome ...)将其添加到URL中,您可以尝试删除额外的引号:

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

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

    • 一个
rwqw0loc

rwqw0loc2#

如果其他人也有类似的想法,那么再补充一下,你也可以使用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, "");
5vf7fwbs

5vf7fwbs3#

试试这个

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

或者,使用replace

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

tquggr8v4#

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

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

这将返回如下所示的URL:
“网址(' http://www.example.com/img.png ')”
然后您需要删除此URL中不需要的部分:

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

7jmck4yq5#

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

xdnvmnnf6#

记录到控制台的所有background-image URL,不带括号和引号:

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

相关问题