我试图得到元素的背景图像的宽度和高度。单击它时,应该在元素中显示它(本例中为“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
};这是小提琴。问题在于它只在Chrome中工作,所有其他主要浏览器都返回" 0“。我不知道原因是什么。那个图形不是全装好了吗?
发布于 2013-06-21 22:05:12
问题是有些浏览器给CSS添加了引号,并且它试图加载(在小提琴的例子中) "显示器/%22 http://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;
};发布于 2017-05-05 11:06:00
我想您需要等待图像上的onload事件。
https://stackoverflow.com/questions/17244811
复制相似问题