2012-04-24 47 views
0
$(document).ready(function() { 
    $("img.resizeImage").each(function(){ 
     var img = $(this); 
     var width = $(this).width(); // Current image width 
     var height = $(this).height(); // Current image height 
     // alert("give image size ....."+width+", "+height); 
     var pic_real_width, pic_real_height; 
     $("<img/>").attr("src", $(img).attr("src")) 
      .load(function() { 
       pic_real_width = this.width; 
       pic_real_height = this.height; 

      }); 

     if(pic_real_width < width ){ 
      //alert("display original width.sssss 103.."); 
      $(this).removeAttr("width"); 
      $(this).css("width",pic_real_width); 
     } 

     if(pic_real_height < height){ 
      //alert("display original height ss.102.."); 
      $(this).removeAttr("height"); 
      $(this).css("height",pic_real_height); 
     } 
    }); 
}); 

在上面的jQuery執行流程中,如果條件不匹配,我沒有獲得期望的結果。如果我在兩個if()s之上保留一些警報,那麼執行流程會在兩個條件之內進入。 pl幫助我。 如何可以逐行執行jquery語句..JQuery-爲每個具有類的img元素添加css

回答

3

您的圖像加載是異步的,這意味着.load回調不會馬上被調用。

因此,pic_real_widthpic_real_height在您嘗試使用它們時未知。

也許你應該將這兩個條件轉換成的回調函數?

+0

那麼我怎樣才能得到每個img元素的原始高度和寬度沒有負載。任何其他解決方案。我想要的是如果圖像小於給定的高度和寬度我不希望它被拉伸,以原始高度和寬度顯示圖像。 – MadhuB 2012-04-24 10:10:38

+0

而不是檢查圖像大小和刪除高度/寬度如果圖像較小,爲什麼不嘗試最大高度和最大寬度的CSS屬性? img {max-width:100px;}將導致圖像永遠不會被拉伸,而較大的圖像永遠不會超過100像素的寬度。 – 2012-04-24 10:17:13

+0

謝謝。我可以使用最大寬度和最大高度。 – MadhuB 2012-04-26 09:07:32

相關問題