3

DOM がロードされた後、Chrome に画像の幅または高さを認識させるのに問題があります。画像は、phpThumb スクリプト (画像のサイズを変更する) によって動的に読み込まれます。動的 URL を削除して画像の直接 URL に置き換えると、問題は発生せず、すべてが Chrome で機能しますが、動的 URL では、クロムは画像の幅または高さを計算できないようです。

誰でもこれを経験したことがありますか?それは私の頭をやっています。

問題のコードは次のとおりです。

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 に答える