문제

I have my html

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

and I use javascript to get the size of the image

    $('.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);



    })

when I try to alert it, it says 0, or if I use $('#preview_pic').clientWidth, it says undefined

도움이 되었습니까?

해결책

You should preload image and on the load event of image get its height and width

$('.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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top