无法获得图像的宽度

时间:2014-02-02 21:28:45

标签: javascript jquery html image image-size

我有我的HTML

<div id="image_preview_wrapper"><img id="preview_pic" src=""></div>

我用javascript来获取图片的大小

    $('.p_photo_image').click(function(){

    //just get the thumb 
    //image src and put it in the preview image src

    var clicked_image=$(this).attr('src'); 
    $('#preview_pic').attr('src',clicked_image);

    var pre_width=$('#preview_pic').width();
    var pre_height=$('#preview_pic').height();

    alert(pre_width);
    alert(pre_height);



    })

当我尝试提醒它时,它会显示0,或者如果我使用$('#preview_pic')。clientWidth,则表示未定义

1 个答案:

答案 0 :(得分:0)

您应该预先加载图像,并在图像的加载事件中获取其高度和宽度

$('.p_photo_image').click(function () {
    //just get the thumb 
    //image src and put it in the preview image src
    var clicked_image = $(this).attr('src');

    //Preload image
    var img = new Image();
    img.src = clicked_image;
    img.onload = function () { 
        alert("height: " + this.height + " width:" + this.width);
        $('#preview_pic').attr('src', this.src);            
    };
})

DEMO