我可以获得 div 的背景图像 url 吗?
我有一个按钮,当我单击它时,我想提醒 #div1
的 background-image
URL。
是否可以?
I have a button of which when I click it I want to alert the background-image
URL of #div1
.
Is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
如果可能的话,我通常更喜欢
.replace()
而不是正则表达式,因为它通常更容易阅读: http://jsfiddle.net/mblase75/z2jKA/2I usually prefer
.replace()
to regular expressions when possible, since it's often easier to read: http://jsfiddle.net/mblase75/z2jKA/2是的,这是可能的:
Yes, that's possible:
我稍微改进了答案,它处理扩展的 CSS 定义,例如:
JavaScript 代码:
结果:
I have slightly improved answer, which handles extended CSS definitions like:
JavaScript code:
Result:
正如已经提到的,Blazemongers 解决方案无法删除引号(例如由 Firefox 返回)。因为我发现 Rob Ws 的解决方案相当复杂,所以在这里添加我的 2 美分:
As mentioned already, Blazemongers solution is failing to remove quotes (e.g. returned by Firefox). Since I find Rob Ws solution to be rather complicated, adding my 2 cents here:
我认为为此使用正则表达式是错误的,主要是因为
由于 url(" 和 ") 组件是不变的,请像这样修剪字符串:
I think that using a regular expression for this is faulty mainly due to
Since the url(" and ") components are constant, trim your string like so:
我正在用这个
I'm using this one
这是一个简单的正则表达式,它将从返回的字符串中删除
url("
and")
。Here is a simple regex which will remove the
url("
and")
from the returned string.仅使用一次
replace
调用(正则表达式版本):<代码>
var bgUrl = $('#element-id').css('背景图像').replace(/url\(("|')(.+)("|')\)/gi, '$2' );
Using just one call to
replace
(regex version):var bgUrl = $('#element-id').css('background-image').replace(/url\(("|')(.+)("|')\)/gi, '$2');
我的两分钱。
如果 CSS 中的 background-image 属性被 background 属性覆盖,那么这些解决方案都不起作用。
假设您设置了 background-image 属性,并且您不想在浏览器中看到它,您只需要出于某种目的在 jQuery 中获取该值。
因此,如果您有这样的内容:
则
$('div').css('background-image');
返回 none网址。如果您需要将背景保持为白色,并在 jQuery 中获取background-image URL值,则替换背景 与 伪元素,如下所示:
现在
$('div').css('background-image');
返回URL('url-here.jpg'),而不是无。My two cents.
None of these solutions work if the background-image property is overwritten in CSS by the background property.
Let's say you have the background-image property set and you don't want to see it in the browser, you just need to get the value in jQuery for some purpose.
So, if you have something like this:
Then
$('div').css('background-image');
returns none instead the URL.If you need to keep background white and also to get the background-image URL value in jQuery then replace the background with pseudo-element, like this:
Now
$('div').css('background-image');
returns URL('url-here.jpg') instead none.