我试图获取元素的背景图像的宽度和高度。当你点击它时,它应该在元素内显示它(在这种情况下为“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”。我不知道是什么原因。这个图形是不是完全加载?
谢谢,我从来没有已经猜到这是问题了 –
如果有疑问,打开网络检查器和'console.log()';)让我失望的是FF无法加载具有该奇怪URL的图像。 – SpenserJ