Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

javascript - jQuery width() and height() return 0 for img element

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...