如何在JavaScript中获得<div>
元素的background-image
URL?
例如,我有这个:
<div style="background-image:url('http://www.example.com/img.png');">...</div>
我如何获得just的background-image
的URL?
如何在JavaScript中获得<div>
元素的background-image
URL?
例如,我有这个:
<div style="background-image:url('http://www.example.com/img.png');">...</div>
我如何获得just的background-image
的URL?
您可以try 这样做:
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:个
根据@Miguel和下面的其他 comments ,如果您的浏览器(IE/FF/Chrome.)将其添加到url:
bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
如果它可能包含单引号,请使用:replace(/['"]/g, "")
100