簡體   English   中英

如何使用 JavaScript 獲取元素的背景圖片 URL?

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

如何在 JavaScript 中獲取<div>元素的background-image URL? 例如,我有這個:

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

我怎么會得到的只是URL background-image

你可以試試這個:

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>

編輯:

根據@Miguel 和下面的其他評論,如果您的瀏覽器(IE/FF/Chrome...)將其添加到 url,您可以嘗試刪除額外的引號:

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

如果可能包含單引號,請使用: replace(/['"]/g, "")

演示小提琴

為了以防萬一其他人有類似的想法,您也可以使用正則表達式:

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

試試這個:

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

首先,您需要返回您的背景圖片內容:

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

登錄以控制台所有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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM