2013-06-21 181 views
2

我试图获取元素的背景图像的宽度和高度。当你点击它时,它应该在元素内显示它(在这种情况下为“200 300”)。获取背景图像的尺寸

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 
}; 

这里的Fiddle。问题是只有在Chrome中,才起作用,所有其他主要浏览器都返回“0 0”。我不知道是什么原因。这个图形是不是完全加载?

回答

3

问题是某些浏览器向CSS添加了引号,并且它试图加载(在小提琴的情况下)“http://fiddle.jshell.net/_display/%22http://placehold.it/200x300%22”。我已经更新您的.replace()找人“,以及和小提琴是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; 
}; 
+0

谢谢,我从来没有已经猜到这是问题了 –

+0

如果有疑问,打开网络检查器和'console.log()';)让我失望的是FF无法加载具有该奇怪URL的图像。 – SpenserJ

0

我猜你需要等待图像onload事件。