如何在JavaScript中获取元素的background-image
URL <div>
?例如,我有这个:
<div style="background-image:url('http://www.example.com/img.png');">...</div>
Run Code Online (Sandbox Code Playgroud)
我怎么会得到公正的网址background-image
?
pal*_*aѕн 78
你可以试试这个:
var img = document.getElementById('your_div_id'),
style = img.currentStyle || window.getComputedStyle(img, false),
bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
Run Code Online (Sandbox Code Playgroud)
// 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);
Run Code Online (Sandbox Code Playgroud)
<div id="testdiv" style="background-image:url('http://placehold.it/200x200');"></div>
Run Code Online (Sandbox Code Playgroud)
编辑:
根据@Miguel和下面的其他评论,如果您的浏览器(IE/FF/Chrome ...)将其添加到网址,您可以尝试删除其他引号:
bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
Run Code Online (Sandbox Code Playgroud)
如果它可能包括单引号,请使用: replace(/['"]/g, "")
saw*_*yer 16
只是为了增加这个以防其他人有类似的想法,你也可以使用正则表达式:
var url = backgroundImage.match(/url\(["']?([^"']*)["']?\)/)[1];
Run Code Online (Sandbox Code Playgroud)
然而,根据jsPerf的说法,@ Praveen的解决方案似乎在Safari和Firefox中表现得更好:http://jsperf.com/match-vs-slice-and-replace
如果您想考虑值包含引号但不确定是双引号还是单引号的情况,您可以执行以下操作:
var url = backgroundImage.slice(4, -1).replace(/["']/g, "");
Run Code Online (Sandbox Code Playgroud)
var url = document.getElementById("divID").style.backgroundImage;
alert(url.substring(4, url.length-1));
Run Code Online (Sandbox Code Playgroud)
replace
url.replace('url(','').replace(')','');
// Or...
backgroundImage.slice(4, -1).replace(/["']/g, "");
Run Code Online (Sandbox Code Playgroud)
首先,您需要返回背景图片内容:
var img = $('#your_div_id').css('background-image');
Run Code Online (Sandbox Code Playgroud)
这将返回如下URL:
“网址(' http://www.example.com/img.png ')”
然后,您需要删除此URL不需要的部分:
img = img.replace(/(url\(|\)|")/g, '');
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
59449 次 |
最近记录: |