Get image size when it loads from an extern URL in Javascript

时光总嘲笑我的痴心妄想 提交于 2020-01-01 20:58:21

问题


I need to know the image size when it loads from an extern URL because the project needs to resize the image div.

I need to do something like this:

<img id="imglegend'+layername+'" src="url_to_an_extern_host" />

And, using Javascript and JQuery:

$('#imglegend'+layername).ready(function(){
   var h = $('#imglegend'+layername);
   // Resize image div container
});

But this didn't work. Is it possible to do?

Thanks in advance!


回答1:


$('#imglegend').load(function(){
   var w =    $(this).width();
   var h =    $(this).height();
   alert(w); alert(h);
}).error(function (){
   $(this).remove();//remove image if it fails to load// or what ever u want
})



回答2:


Images don't have a ready event. They do however have a load event:

$('#imglegend'+layername).load(function(){
   alert(this.width);
});

EDIT: BTW, you need to make sure that the image isn't loaded before you attach the event handler. You'll wither need to assign the src in your script after assigning the handler instead of in your HTML, or assign the handler in the onload HTML instead.



来源:https://stackoverflow.com/questions/4713470/get-image-size-when-it-loads-from-an-extern-url-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!