Can't get ajax - loaded image's height and width via jquery

旧巷老猫 提交于 2019-12-24 10:35:10

问题


I'm loading an image exteranlly via ajax like so...

function load_image(image_href) {

    var img = new Image();
    $(img).load(function () { 
        $(this).hide(); $('#a_box').append(this); 
        $(this).fadeIn(); 
        }, gallery_image_load_complete()
    ).error(function () {
    }).attr('src', image_href);

}

function gallery_image_load_complete() {
    conslole.log('complete')

     $('#a_box img').height(); //wrong numbers, as though the image is partially loaded
     $('#a_box img').width(); //wrong numbers
}

The problem is I'm trying to get the loaded image's height and width inside the function gallery_image_load_complete(). For some reason, this image height and width are off, it's astohugh the image hasn't fully loaded.

Can someone help me out please?


回答1:


gallery_image_load_complete() needs to be called within the load event handler:

function load_image(image_href) {

    var img = new Image();
    $(img).load(function () { 
        $(this).hide(); $('#a_box').append(this); 
        $(this).fadeIn(); 
        gallery_image_load_complete(); // now inside the load event handler
    }).error(function () {
    }).attr('src', image_href);

}



回答2:


You do know that the height and width attributes tell you the size of the image object in the DOM, not the underlying image files themselves, right?




回答3:


I don't have the code handy right now, but when I needed the size of an arbitrary image in order to decide how to present it, I preload in a hidden element and get the size of the element @ loaded. then do what you will and place the image where it is needed.

works well.



来源:https://stackoverflow.com/questions/2686724/cant-get-ajax-loaded-images-height-and-width-via-jquery

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