Get image dimensions
I think a somehwat simple problem, but i c开发者_如何转开发an't find any solutions. I need to get the image dimensions from an image that is not yet loaded, but have no clue how.
I have the following html
<a href="http://domain.com/folder/bigImage.jpg" id="someID">
<img src="http://domain.com/folder/smallImage.jpg">
</a>
Now i want to get the image dimensions of the big image, but how?
$("#someID").click(function(event){
event.preventDefault();
image = this.href;
newImage = new Image();
newImage.src = image;
alert(newImage.width);
});
or
$("#someID").click(function(event){
event.preventDefault();
image = this.href;
newImage = new Image();
newImage.src = image;
newImage.load(function(){
alert(newImage.width);
});
});
both don't work
.load()
is a jQuery function so you need a wrapper, and bind it before setting the src
, like this:
$("#someID").click(function(event){
event.preventDefault();
var newImage = new Image();
$(newImage).load(function(){
alert(this.width);
});
newImage.src = this.href;
});
Your second example is close; you need to wait for the image to load first, before you can retrieve the dimensions of it.
$('#someId').bind('click', function (event) {
var image = new Image();
image.onload = function () {
var height = this.height;
var width = this.width;
alert(height + " | " + width);
}
image.src = this.href;
event.preventDefault();
});
You can see a working fiddle here: http://www.jsfiddle.net/JsRmU/
精彩评论