如何通过 JavaScript 确定 div 的背景图片 URL?

新手上路,请多包涵

我发现了很多关于如何使用 JavaScript 更改 div 的背景图像的信息,但我正在尝试使用 JavaScript 来确定正在显示的背景图像。设置图像的代码如下:

 document.getElementById("widgetField").style.background="url(includes/images/datepicker_open.png)";

我已经尝试了所有我能想到的访问背景图片 url 的组合,但到目前为止还没有成功:

 alert(document.getElementById("widgetField").style.backgroundImage.url);  - returns Undefined
alert(document.getElementById("widgetField").style.backgroundImage);  - empty response
alert(document.getElementById("widgetField").style.background);
alert(document.getElementById("widgetField").style.background.image);
alert(document.getElementById("widgetField").style.background.url);
alert(document.getElementById("widgetField").style.background.image.url);
alert(document.getElementById("widgetField").style.background.value);
alert(document.getElementById("widgetField").style.background.image.value);
alert(document.getElementById("widgetField").style.background.image.value);
alert(document.getElementById("widgetField").style.backgroundImage.value);

有谁知道如何做到这一点?可能吗?

顺便说一句,这是一开始在 CSS 中设置图像的方式:

 #widgetField {
    width: 290px;
    height: 26px;
    background: url(../images/datepicker_closed.png);
    overflow: hidden;
    position: relative;
}

更新:

如果我运行以下命令,它将起作用:

 document.getElementById("widgetField").style.background="url(includes/images/datepicker_open.png)";
alert(document.getElementById("widgetField").style.background);

但是,我似乎无法访问 URL 属性,直到它被 JavaScript 设置,即使它已经在 CSS 文件中定义。是否存在无法访问原始 CSS 设置的原因?

原文由 user77413 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 455
2 个回答

尝试这个:

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

原文由 Mic 发布,翻译遵循 CC BY-SA 2.5 许可协议

You’re setting the background property, background and backgroundImage are two seperate properties which is why backgroundImage is empty after setting background 。如果只想访问背景属性的 url 部分,可以使用以下代码:

 var wfBg = document.getElementById("widgetField").style.background;
var wfBgUrl = wfBg.match(/(url\(['"]?([^)])['"]?\))/i);

if (wfBgUrl)
{
    // Add your code here. wfBgUrl[1] is full string including "url()",
    // wfBgUrl[2] would be just the url inside the parenthesis
}

对于css文档设置的样式:

 if (window.getComputedStyle) // For standards compliant browsers
    var wfBg = window.getComputedStyle(
        document.getElementById("widgetField")
    ).getPropertyValue("background");
else // for IE
    var wfBg = document.getElementById("widgetField").currentStyle.background;

原文由 Andy E 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题