jQuery/javascript - 加载前获取图像大小

Sup*_*nja 5 javascript jquery

我有一个上传后呈现为缩略图的图像列表.我的问题是我需要完全上传的图像的尺寸,以便我可以运行调整大小功能,如果大小不正确.

构建图像列表的功能

function buildEditList(json, galleryID)
{
    //Hide the list
    $sortable = $('#sortable');
    $sortable.hide();

    for(i = 0, j = json.revision_images.length; i < j; i++) {
        $sortable.append(
            "<li id='image_" + json.revision_images[i].id + "'><a class=\"ui-lightbox\" href=\"../data/gallery/"
            + galleryID
            + "/images/album/"
            + json.revision_images[i].OrgImageName
            + "\"><img id=\""
            + json.revision_images[i].id
            + "\" alt=\"\" src=\"../data/gallery/"
            + galleryID 
            + "/images/album/" 
            + json.revision_images[i].OrgImageName 
            + "\"/></a></li>"
        ).hide();
    }
    //Set first and last li to 50% so that it fits the format
    $('#sortable li img').first().css('width','50%');
    $('#sortable li img').last().css('width', '50%');

    //Fade images back in 
    $sortable.fadeIn("fast",function(){
        var img = $("#703504"); // Get my img elem -- hard coded at the moment
        var pic_real_width, pic_real_height;
        $("<img/>") // Make in memory copy of image to avoid css issues
            .attr("src", $(img).attr("src"))
            .load(function() {
                pic_real_width = this.width;   // Note: $(this).width() will not
                pic_real_height = this.height; // work for in memory images.
        });
        alert(pic_real_height);
    });

}
Run Code Online (Sandbox Code Playgroud)

我一直在尝试使用此stackoverflow帖子中的解决方案,但还没有让它工作,或者它可能只是我的代码.如果您对此有任何想法,我可以使用帮助.目前警报未定义.

Syo*_*yon 2

有一个名为naturalHeight 或naturalWidth 的较新的js 方法将返回您正在查找的信息。不幸的是,它无法在旧版 IE 中运行。这是我几个月前创建的一个函数,可能对您有用。我在下面添加了一些代码作为示例:

\n\n
function getNatural($mainImage) {\n    var mainImage = $mainImage[0],\n        d = {};\n\n    if (mainImage.naturalWidth === undefined) {\n        var i = new Image();\n        i.src = mainImage.src;\n        d.oWidth = i.width;\n        d.oHeight = i.height;\n    } else {\n        d.oWidth = mainImage.naturalWidth;\n        d.oHeight = mainImage.naturalHeight;\n    }\n    return d;\n}\n\nvar img = $("#703504");\nvar naturalDimension = getNatural(img);\nalert(naturalDimension.oWidth, naturalDimension.oHeight)\xe2\x80\x8b\n
Run Code Online (Sandbox Code Playgroud)\n

  • 我不明白为什么这会起作用。至少必须从服务器返回“某些东西”才能知道宽度/高度。该返回将是异步的,而上面的代码就像同步一样编写,因此可以使用浏览器已缓存的图像。但是未缓存的图像怎么样? (8认同)