2012-03-06 61 views
1

我需要使圖像適合視口/窗口大小。使圖像適合視口

我用這個代碼做:

$(".fittedImg").each(function() { 

     // I want to limit the size, and show a scrollbar on very small viewport 
     height = ($(window).height() < 725) ? 725 : $(window).height(); 
     width = ($(window).width() < 1150) ? 1150 : $(window).width(); 

     var newWidth, newHeight; 
     $(this) 
      .removeAttr("height") 
      .removeAttr("width"); // reset img size 

     // calculate dimension and keep it 
     if (($(this).width()/width) > ($(this).height()/height)) { 
      newHeight = height; 
      newWidth = height/($(this).height()/$(this).width()); 

     } else { 
      newHeight = width/($(this).width()/$(this).height()); 
      newWidth = width; 
     }; 
     $(this).stop(true, false).animate({ 
      "height": newHeight + "px", 
      "width": newWidth + "px" 
     }); 
}); 

我裹在我上調整大小調用一個函數的代碼,並在活動,如$(「fittedImg。」)load()和$。 ( '.fittedImg')。就緒()。

結果非常奇怪: 在Chrome中,它通常有效,但有時圖像會在重複刷新時延長。在IE瀏覽器上也有相同的問題。歌劇不會永遠不會失敗,Safari會忽略計算(永遠不會延伸)。

我的計算和/或事件調用有什麼問題?

謝謝。

回答

3
  1. 確保圖像提取寬度/高度
  2. 不要取下計算

假設你之前的寬度/高度屬性完全加載之後要適應包含元素內的圖像(在這種情況下,window),這裏有一些更簡單的計算,你可能會覺得有用。這個概念很簡單,根據包含的度量和圖像度量,計算比率。然後與原來的措施相乘:

$(".fittedImg").load(function(){ 

    var imgWidth = this.width, 
     imgHeight = this.height, 
     winWidth = $(window).height(), 
     winHeight = $(window).width(), 
     ratio = Math.min(winWidth/imgWidth, winHeight/imgHeight); 

    // if you don’t want it to upscale, use Math.min or Math.max on the ratio 

    $(this).stop(true, false).animate({ 
     height: imgHeight*ratio, 
     width: imgWidth*ratio 
    }); 
}); 

請注意,一些擴展(如AdBlock)可以搞砸從圖像中提取的寬度/高度。您可以控制和編輯imgWidth/imgHeight,以確保它可用。

另請注意,根據您的代碼放置方式,添加此事件時可能已經加載了您的圖片。在這種情況下,您應該檢查IMG元素上的complete屬性:

$('fittedImg').each(function() { 
    $(this).load(function() { 
     // the calculations goes here 
    }); 
    if (this.complete) { // check if image is already loaded 
     $(this).trigger('load'); 
    } 
}); 
+0

1.我該怎麼做? load()和ready()不夠好? 2.沒有幫助。 – SRachamim 2012-03-06 10:47:24

+0

看我的例子作爲樣板。 '.load()'應該足以獲得寬度/高度,但是您可以在處理程序中調整值以確保。 – David 2012-03-06 10:50:13