简体   繁体   English

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

[英]How to get background image URL of an element using JavaScript?

How would I get the background-image URL of a <div> element in JavaScript?如何在 JavaScript 中获取<div>元素的background-image URL? For example, I have this:例如,我有这个:

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

How would I get just the URL of the background-image ?我怎么会得到的只是URL background-image

You can try this:你可以试试这个:

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

 // 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);
 <div id="testdiv" style="background-image:url('http://placehold.it/200x200');"></div>

Edit:编辑:

Based on @Miguel and other comments below, you can try this to remove additional quotation marks if your browser (IE/FF/Chrome...) adds it to the url:根据@Miguel 和下面的其他评论,如果您的浏览器(IE/FF/Chrome...)将其添加到 url,您可以尝试删除额外的引号:

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

and if it may includes single quotation, use: replace(/['"]/g, "")如果可能包含单引号,请使用: replace(/['"]/g, "")

DEMO FIDDLE演示小提琴

Just to add to this in case anyone else has a similar idea, you could also use Regex:为了以防万一其他人有类似的想法,您也可以使用正则表达式:

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

However it seems like @Praveen's solution actually performs better in Safari and Firefox, according to jsPerf: http://jsperf.com/match-vs-slice-and-replace然而,根据 jsPerf: http ://jsperf.com/match-vs-slice-and-replace,似乎@Praveen 的解决方案实际上在 Safari 和 Firefox 中表现更好

If you want to account for cases where the value includes quotes but are unsure whether it's a double or single quote, you could do:如果您想考虑值包含引号但不确定它是双引号还是单引号的情况,您可以执行以下操作:

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

Try this:试试这个:

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

Or, using replace :或者,使用replace

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

First of all you need to return your background-image content:首先,您需要返回您的背景图片内容:

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

This will return the URL as following:这将返回如下 URL:

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

Then you need to remove the un-wanted parts of this URL:然后您需要删除此 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}`); }); }

Log to console all background-image URLs, without parentheses and quotes:登录以控制台所有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]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript获取元素背景图片,但消除“ url()” - Javascript get element background image BUT eliminate the “url()” 如何使用JavaScript或Selenium获取图像的背景URL - How to get the background url of the image using the javascript or selenium 如何使用javascript在html中获取元素背景图像 - How to get the element background image in html using javascript 如何使用element.style.backgroundImage =“ url(filePath)”将背景图像添加到javascript? - How do I add a background image to javascript using element.style.backgroundImage = “url(filePath)”? 如何使用Javascript基于图像URL切换背景图像 - How to Toggle background image based on Image URL using Javascript 如何使用 JavaScript 从用户输入 (URL) 更改背景图像 - How to change background image from user input (URL) using JavaScript 如何使用Javascript在CSS中动态设置背景图片网址 - How to dynamically set background image url in CSS using Javascript 如何使用 Selenium 和 Javascript 从背景图像中检索 url - How to retrieve the url from background image using Selenium and Javascript 如何使用CSS动画/ JavaScript使具有背景图像的元素出现 - How to make an element with background image appear using css animation/javascript 在jQuery中,如何在不使用JavaScript对图像的URL进行硬编码的情况下设置元素的背景图像? - In jquery, how can I set the background-image of an element without hardcoding the url of the image in my javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM