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

我有一个上传后以缩略图forms呈现的图像列表。 我遇到的问题是我需要完全上传的图像的尺寸,以便我可以运行resizefunction,如果大小不正确。

构建图像列表的function

function buildEditList(json, galleryID) { //Hide the list $sortable = $('#sortable'); $sortable.hide(); for(i = 0, j = json.revision_images.length; i < j; i++) { $sortable.append( "
  • " ).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; $("") // 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); }); }

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

    有一个名为naturalHeight或naturalWidth的更新的js方法将返回您正在寻找的信息。 不幸的是,它不适用于较旧的IE版本。 这是我几个月前创建的一个可能对你有用的function。 我在下面添加了一些代码作为示例:

     function getNatural($mainImage) { var mainImage = $mainImage[0], d = {}; if (mainImage.naturalWidth === undefined) { var i = new Image(); i.src = mainImage.src; d.oWidth = i.width; d.oHeight = i.height; } else { d.oWidth = mainImage.naturalWidth; d.oHeight = mainImage.naturalHeight; } return d; } var img = $("#703504"); var naturalDimension = getNatural(img); alert(naturalDimension.oWidth, naturalDimension.oHeight)​