3

在 DOM 加载后,我无法让 Chrome 识别图像宽度或高度。图像是通过 phpThumb 脚本(调整图像大小)动态加载的。如果我拿走动态 url 并用图像的直接 url 替换它,我没有问题,一切都在 Chrome 中工作,但使用动态 url,chrome 似乎无法计算图像的宽度或高度。

有人对此有经验吗?它让我头疼。

有问题的代码是:

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

其中imgwidth = 0;对于 chrome,但 IE、Firefox 都报告正确的大小。

4

2 回答 2

5

正确的代码是 .onload 和以下函数:

var theImage     = new Image();
theImage.src     = $image.attr('src');
theImage.onload = function(){
    var imgwidth     = $(this).width;
    var imgheight    = $(this).height; 
});
于 2011-06-04T04:44:43.260 回答
0

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>');
    });
});​
于 2012-04-12T04:57:13.447 回答