简体   繁体   中英

Finding image size without it being loaded

I've created a simple modal window to a large version of a thumbnail, to position the image centre screen I need the image size. I've tried .load but can't seem to get anything to work - on the second click it works OK as the image as been loaded, unfortunately with a width and height of 0.

$(function(){
$(".quickImg").click(function(){ 
    var imageSrc = 'images/'+$(this).attr('rel')+'/'+$(this).attr('href').replace('#', '')+'_full.jpg';
    var imgSize = new Image(); 
    imgSize.src = imageSrc;
IMAGE LOADING HERE
    var imgW = imgSize.width,imgH = imgSize.height;
    var imgDiv='<div id="qrBlock"></div><div id="newsModal" style="margin-left:-'+imgW/2+'px;margin-top:-'+imgH/2+'px"><a href="#" title="Close Window" class="closeQR">X</a><img src="'+imageSrc+'" width="'+imgW+'" height="'+imgH+'" /></div>'
    $('body').append(imgDiv);
});
});

You should wait for image to load to get its width and height. To do that first you have to attach onload event to an image and a callback to execute when image is loaded:

   $(function(){
        $(".quickImg").click(function(){ 
            var imageSrc = 'images/'+$(this).attr('rel')+'/'+$(this).attr('href').replace('#', '')+'_full.jpg';
            var imgSize = new Image(); 
            imgSize.onload = function(){
                var imgW = this.width,
                    imgH = this.height,
                    imgDiv = '<div id="qrBlock"></div><div id="newsModal" style="margin-left:-'+imgW/2+'px;margin-top:-'+imgH/2+'px"><a href="#" title="Close Window" class="closeQR">X</a><img src="'+imageSrc+'" width="'+imgW+'" height="'+imgH+'" /></div>';
                    $('body').append(imgDiv);
            }

            imgSize.src = imageSrc;
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM