DOM elements have dimensions only when added to a parent, as dimension is determined by the rendering engine. To go around this issue, have a <div>
container absolutely positioned off screen, add the image to it first, get the dimension, then add the image at it's final destination.
Something like :
var _offscreen = $('<div></div>')
.css({position:'absolute',left:'-999999px',width:'400px',height:'600px'})
.appendTo($('body'));
var img = $('<img>/img>')
.attr('src',"http://l1.yimg.com/a/i/ww/news/2011/03/25/zo.jpg")
.load(function() {
var $this = $(this);
$this.appendTo(_offscreen);
setTimeout(function() {
var width = $this.width();
var height = $this.height();
alert($this.attr('src') + ' = ' + width + "x" + height);
}, 0);
});
** EDIT **
I just updated the code above. As it turned out, you need to let the rendering engine draw the image (of course!) and then get the dimension. So that edit works.
This could be put inside a convenient function like :
$('imageElement').loadImage("path/to/image", function() {
alert("Image " + $(this).attr('src') + " loaded: " + $(this).width() + "x" + $(this).height());
});
** UPDATE **
I thought you might like to see the code above put into a JQuery plugin... just for fun :) It just works, there is no validation done (i.e. it won't check if you pass other elements than <img>
), and if the selector returns more than one element, the plugin will load the same image into each selected elements. You could actually have the plugin argument url
be an array (optional) and load each image of the array in each selected element, etc. Just a thought.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…