Jquery Chrome image width and height = 0 for new image ()

I'm having a problem with Chrome recognizing the width or height of the image after loading the DOM. The image is dynamically loaded through a phpThumb script (which resizes the image). If I pick up the dynamic url and just replace it with the direct url of the image, I don't get any problems and everything works in Chrome, but with the dynamic url, chrome doesn't seem to be able to calculate the width or height of the image.

Does anyone have any experience? He makes my head.

This code:

var theImage     = new Image();
theImage.src     = $image.attr('src');
var imgwidth     = theImage.width;
var imgheight    = theImage.height;

Where imgwidth = 0; for chrome, but IE, Firefox report the correct size.

+3
source share
2 answers

The correct code is .onload and the following function:

var theImage     = new Image();
theImage.src     = $image.attr('src');
theImage.onload = function(){
    var imgwidth     = $(this).width;
    var imgheight    = $(this).height; 
});
+5
source

http://jsfiddle.net/cyrilkong/XJUGt/4/

function imgRealSize(img) {
    var $img = $(img);
    if ($img.prop('naturalWidth') === undefined) {
        var $tmpImg = $('<img/>').attr('src', $img.attr('src'));
        $img.prop('naturalWidth', $tmpImg[0].width);
        $img.prop('naturalHeight', $tmpImg[0].height);
    }
    return {
        'width': $img.prop('naturalWidth'),
        'height': $img.prop('naturalHeight')
    };
}

$(function() {
    var target = $('img.dummy');
    var target_native_width;
    var target_native_height;
    target.each(function(index) {
        // console.log(index);
        imgRealSize(this[index]);
        target_native_width = $(this).prop('naturalWidth');
        target_native_height = $(this).prop('naturalHeight');
        $(this).parent('div').append('<p>This image actual size is ' + target_native_width + ' x ' + target_native_height + ', and css is ' + $(this).width() + ' x ' + $(this).height() + '.</p>');
    });
});​
0

Source: https://habr.com/ru/post/1796374/


All Articles