Getting dimensions of background-image

泪湿孤枕 提交于 2019-12-08 02:16:55

问题


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.



来源:https://stackoverflow.com/questions/17244811/getting-dimensions-of-background-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!