Jquery; Chrome Image Width and Height = 0 for new Image()

僤鯓⒐⒋嵵緔 提交于 2019-12-12 16:04:50

问题


Im having trouble getting Chrome to recognize an Image width or height after the DOM has loaded. The Image is dynamically loaded through phpThumb script (which resizes the image). If I take away the dynamic url and just replace it with the Image's direct url I get no issues and everything works in Chrome but with the dynamic url, chrome doesn't seem to be able to calculate the image width or height.

Anyone have any experience with this? Its doing my head in.

The code in question is :

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

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


回答1:


The right 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; 
});



回答2:


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>');
    });
});​


来源:https://stackoverflow.com/questions/5198094/jquery-chrome-image-width-and-height-0-for-new-image

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