2012-12-13 45 views
5

我有一個上傳後呈現爲縮略圖的圖像列表。我的問題是我需要完全上傳的圖像的尺寸,以便我可以運行調整大小功能,如果大小不正確。jQuery/javascript - 在加載之前獲取圖像大小

功能是建立在圖像列表

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

} 

我一直在嘗試使用此stackoverflow後的解決方案,但還沒有得到它的工作,或者它可能只是我的代碼。如果你對此有任何想法,我可以使用幫助。目前該警報尚未定義。

+0

聽起來像我會做服務器端的東西。 – Jeroen

+0

請更具體地說明發生了什麼問題。 – Mark

+0

@Mark - 目前我的警報(pic_real_width)未定義。 – Bungdaddy

回答

2

有一個名爲naturalHeight或naturalWidth的更新的js方法,它將返回您正在查找的信息。不幸的是,它不適用於較舊的IE版本。這是我幾個月後創建的功能,可能適合您。我在下面添加了一段代碼,例如:

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)​ 
+0

非常棒的人,正是我所需要的。 – Bungdaddy

+8

我看不出爲什麼這會起作用。至少* *必須已經從服務器返回,以瞭解寬度/高度。該返回將是異步的,而上面的代碼被寫爲好像是同步的,所以可能與瀏覽器已緩存的圖像一起工作。但未經緩存的圖像怎麼樣? –

+1

我不斷爲我的所有圖像獲取自然寬度和高度爲0。也許有什麼@甜菜根 - 甜菜根的評論? – Henrik

相關問題