Getting dimensions of background-image

2019-05-18 14:22发布

问题:

I'm trying to get width and height of element's background-image. When you click on it, it should show it inside the element ("200 300" in this case).

HTML:

<div id='test'></div>

CSS:

#test {
  width: 100px; height: 100px;
  background-image: url(http://placehold.it/200x300);
}

JavaScript:

$('#test').on('click', function () {
  $(this).text(getDimensions($(this)));
});

var getDimensions = function(item) {
  var img = new Image(); //Create new image
  img.src = item.css('background-image').replace(/url\(|\)$/ig, ''); //Source = clicked element background-image
  return img.width + ' ' + img.height; //Return dimensions
};

Here's the Fiddle. The problem is it works only in Chrome, all the other main browsers return "0 0". I have no idea what's the reason. Isn't that graphic fully loaded?

回答1:

The issue is that some browsers add quotes to the CSS, and it was trying to load (in the fiddle's case) "http://fiddle.jshell.net/_display/%22http://placehold.it/200x300%22". I've updated your .replace() to look for " as well, and a fiddle is at http://jsfiddle.net/4uMEq/

$('#test').on('click', function () {
    $(this).text(getDimensions($(this)));
});

var getDimensions = function (item) {
    var img = new Image();
    img.src = item.css('background-image').replace(/url\(|\)$|"/ig, '');
    return img.width + ' ' + img.height;
};


回答2:

I guess you need to wait for onload event on image.