Javascript:获取< div>的背景图片网址 [英] Javascript: Get background-image URL of <div>

查看:256
本文介绍了Javascript:获取< div>的背景图片网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何获得JavaScript中< div> 元素的 background-image 网址?
例如,我有:

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

如何获取 background-image

解决方案

您可以尝试:

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



编辑



根据下面的@Miguel评论,您可以在IE中试试: -

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

a href =http://fiddle.jshell.net/3c6ymrpo/> DEMO FIDDLE


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>

How would I get just the URL of the 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);

Edit:

Based on @Miguel comment below, you can try this for IE:-

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

DEMO FIDDLE

这篇关于Javascript:获取&lt; div&gt;的背景图片网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆