jQuery width()和height()为img元素返回0 [英] jQuery width() and height() return 0 for img element
问题描述
所以我创建了一个新的图像元素,一旦我从AJAX调用获得响应,像这样的图像元数据:
So I am creating a new image element once I get response from AJAX call with image metadata like this:
var loadedImageContainter = $('<div class="loaded-image-container"></div>');
var image = $('<img src="' + file.url + '" alt="">');
loadedImageContainter.append(image);
$('.loading-image').replaceWith(loadedImageContainter);
var width = image.width();
var height = image.height();
console.log(width);
console.log(height);
但宽度()和高度()函数返回0,尽管图像尺寸为30 x 30像素,它在页面上显示正确。我需要得到它的尺寸才能绝对定位图像。
But width() and height() functions are returning 0 although image has 30 x 30 px size and it appears correctly on the page. I need to get its dimensions in order to absolutely position the image.
推荐答案
你需要等到图像加载到有访问宽度和高度数据。
You need to wait until the image has loaded to have access to the width and height data.
var $img = $('<img>');
$img.on('load', function(){
console.log($(this).width());
});
$img.attr('src', file.url);
或使用普通JS:
var img = document.createElement('img');
img.onload = function(){
console.log(this.width);
}
img.src = file.url;
此外,在阅读宽度和高度之前,您无需将图像插入DOM值,所以您可以在计算所有正确位置之前保留 .loading-image
替换。
Also, you don't need to insert the image into the DOM before you read the width and height values, so you could leave your .loading-image
replacement until after you calculate all of the correct positions.
这篇关于jQuery width()和height()为img元素返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!