如何在JavaScript中获得<div>元素的background-imageURL? 例如,我有这个:

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

我如何获得justbackground-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

Css相关问答推荐

如何仅以WooCommerce单一产品页面为目标?

如何在不重叠侧边栏的情况下尽可能使元素居中?

导航栏没有使用nextui获取页面的全部宽度

如何使用 Ant Design 为不同的屏幕尺寸制作自定义组件样式

如何为 MUI Slider 字段中 markLabel 的第一个和最后一个实例提供边距?

Img 未拉伸以满足所需的纵横比

.SVG 文件对象在锚标签下可点击

使 MUI 自动完成打断长词以适合布局

如何在保持默认外观的同时更改 javaFX 中按钮的突出显示 colored颜色

如何在 Tailwind 中使用 `margin: y x;` 速记?

如果父项的不透明度小于 1,则背景过滤器不适用

不能在带有 SCSS 的过滤器灰度内使用 CSS 变量

CSS如何防止键盘向上移动内容?

如何倾斜元素但保持文本正常(未倾斜)

如何在 CSS 中控制列表样式类型光盘的大小?

如何在没有填充区域的情况下背景化 div

为什么在 CSS3 中启用硬件加速会降低性能?

了解 Bootstrap 3 中的网格类( col-sm-# 和 col-lg-# )

CSS关键帧动画CPU占用率高,应该这样吗?

如何将 HTML
显示为内联元素?