【发布时间】:2017-05-05 19:06:00
【问题描述】:
我正在尝试获取元素背景图像的宽度和高度。当您单击它时,它应该在元素内显示它(在本例中为“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”。我不知道是什么原因。那张图不是已经满载了吗?
【问题讨论】:
标签: javascript google-chrome cross-browser background-image