因此,一旦我收到带有图像元数据的 AJAX 调用的响应,我就会创建一个新的图像元素:
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);
尽管图像大小为 30 x 30 像素并且在页面上正确显示,但 width() 和 height() 函数返回 0。我需要获取它的尺寸以便绝对定位图像。
最佳答案
您需要等到图像加载后才能访问宽度和高度数据。
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
替换,直到计算完所有正确的位置。
关于javascript - jQuery width() 和 height() 对于 img 元素返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16084374/