我能得到 Div 的背景图像网址吗?

我有一个按钮,当我点击它,我想提醒 background-image的网址 #div1

有可能吗?

158097 次浏览

Yes, that's possible:

$("#id-of-button").click(function() {
var bg_url = $('#div1').css('background-image');
// ^ Either "none" or url("...urlhere..")
bg_url = /^url\((['"]?)(.*)\1\)$/.exec(bg_url);
bg_url = bg_url ? bg_url[2] : ""; // If matched, retrieve url, otherwise ""
alert(bg_url);
});

I usually prefer .replace() to regular expressions when possible, since it's often easier to read: http://jsfiddle.net/mblase75/z2jKA/2

    $("div").click(function() {
var bg = $(this).css('background-image');
bg = bg.replace('url(','').replace(')','').replace(/\"/gi, "");
alert(bg);
});

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:

$('#div1').click (function(){
url = $(this).css('background-image').replace(/^url\(['"]?/,'').replace(/['"]?\)$/,'');
alert(url);
})

I have slightly improved answer, which handles extended CSS definitions like:

background-image: url(http://d36xtkk24g8jdx.cloudfront.net/bluebar/359de8f/images/shared/noise-1.png), -webkit-linear-gradient(top, rgb(81, 127, 164), rgb(48, 96, 136))

JavaScript code:

var bg = $("div").css("background-image")
bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')

Result:

"http://d36xtkk24g8jdx.cloudfront.net/bluebar/359de8f/images/shared/noise-1.png"

I'm using this one

  function getBackgroundImageUrl($element) {
if (!($element instanceof jQuery)) {
$element = $($element);
}


var imageUrl = $element.css('background-image');
return imageUrl.replace(/(url\(|\)|'|")/gi, ''); // Strip everything but the url itself
}

I think that using a regular expression for this is faulty mainly due to

  • The simplicity of the task
  • Running a regular expression is always more cpu intensive/longer than cutting a string.

Since the url(" and ") components are constant, trim your string like so:

$("#id").click(function() {
var bg = $(this).css('background-image').trim();
var res = bg.substring(5, bg.length - 2);
alert(res);
});

Using just one call to replace (regex version): var bgUrl = $('#element-id').css('background-image').replace(/url\(("|')(.+)("|')\)/gi, '$2');

Here is a simple regex which will remove the url(" and ") from the returned string.

var css = $("#myElem").css("background-image");
var img = css.replace(/(?:^url\(["']?|["']?\)$)/g, "");

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:

<div class="myDivWithBackground">
<p>Lorem Ipsum</p>
</div>
<style>
.myDivWithBackground{
background-image: URL('url-here.jpg')
}
div.myDivWithBackground{
background: #fff!important
}
</style>

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:

<style>
.myDivWithBackground{
background-image: URL('url-here.jpg')
}
div.myDivWithBackground:after{
content: '';
display: block;
width: 100%;
height: 100%;
background: #fff;
top: 0;
position: absolute;
}
div.myDivWithBackground p{
position: relative;
z-index: 9999;
}
</style>

Now $('div').css('background-image'); returns URL('url-here.jpg') instead none.