问题描述
我想要获取元素的背景图像的宽度和高度。当你点击它,它应该显示在元素内(200 300在这种情况下)。
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:
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
};
这是。问题是它仅在Chrome 中起作用,所有其他主要浏览器都返回0 0。我不知道是什么原因。是不是图形完全加载?
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?
推荐答案
问题是一些浏览器添加引号到CSS,加载(在小提琴的情况下)。我已更新您的.replace()寻找以及一个小提琴在
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;
};
这篇关于获取背景图像的尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!