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);
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);
Or with plain JS:
var img = document.createElement('img');
img.onload = function(){
console.log(this.width);
}
img.src = file.url;
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.
That is because your image isn't loaded when you check width
Try using load event this way
$('img').on('load',function(){
// check width
});
您还可以使用备用API $ .load方法:
$('<img src="' + file.url + '" alt="">').load( function(){ <your function implementation> });
As @ahren said earlier the reason is that image not loaded when you tring to get it's sizes.
If you want to fix this without jQuery you can use vanilla JS addEventListener
method:
document.getElementsByTagName('img')[0].addEventListener('load', function() {
// ...
var width = image.width();
var height = image.height();
console.log(width);
console.log(height);
// ...
});
For me it only works with "appendTo"
$('<img src="myImage.jpeg">').load(function(){
$w = $(this).width();
$h = $(this).height();
$(this).remove()
}).appendTo("body")
Try this:
$('.loading-image').replaceWith(loadedImageContainter);
$('.loading-image').load(function(){
var width = image.width();
var height = image.height();
console.log(width);
console.log(height);
});
If you put it inside the AJAX call, that will work too, this is for json method
$.post("URL",{someVar:someVar},function(data){
var totalImgs = $('body').find('img').length;
var image = $('<img src="' + data.file[0].url + '" alt="" id="IMG_'+ totalImgs +'">');
loadedImageContainter.append(image);
$('.loading-image').replaceWith(loadedImageContainter);
var width = $('#IMG_'+totalImgs).width();
var height = $('#IMG_'+totalImgs).height();
},'json');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.