如何使用JavaScript获取元素的背景图片网址? [英] How to get background image URL of an element using JavaScript?
本文介绍了如何使用JavaScript获取元素的背景图片网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取JavaScript中<div>
元素的background-image
URL?
例如,我有这个:
How would I get the background-image
URL of a <div>
element in JavaScript?
For example, I have this:
<div style="background-image:url('http://www.example.com/img.png');">...</div>
我怎么会恰好 background-image
的URL?
推荐答案
您可以尝试以下操作:
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 ...)将其添加到网址中,则可以尝试删除其他引号:
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:
bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
,如果可能包含单引号,请使用:replace(/['"]/g, "")
and if it may includes single quotation, use: replace(/['"]/g, "")
DEMO FIDDLE
这篇关于如何使用JavaScript获取元素的背景图片网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文