2011-07-05 23 views
2

之後的作品我用這個JavaScript來調整,至800像素,在頁面上一個大的(5MB)圖像的最大:的Javascript調整原圖只有F5

<script type="text/javascript"> 
$(document).ready(function() { 
    $('.detailImg').each(function() { 
     var maxWidth = 800; // Max width for the image 
     var maxHeight = 800; // Max height for the image 
     var ratio = 0; // Used for aspect ratio 
     var width = $(this).width(); // Current image width 
     var height = $(this).height(); // Current image height 

     // Check if the current width is larger than the max 
     if (width > maxWidth) { 
      ratio = maxWidth/width; // get ratio for scaling image 
      $(this).css("width", maxWidth); // Set new width 
      $(this).css("height", height * ratio); // Scale height based on ratio 
      height = height * ratio; // Reset height to match scaled image 
      width = width * ratio; // Reset width to match scaled image 
     } 

     // Check if current height is larger than max 
     if (height > maxHeight) { 
      ratio = maxHeight/height; // get ratio for scaling image 
      $(this).css("height", maxHeight); // Set new height 
      $(this).css("width", width * ratio); // Scale width based on ratio 
      width = width * ratio; // Reset width to match scaled image 
     } 
    }); 
}); 

當加載頁面圖像沒有調整大小。在FireBug控制檯上沒有錯誤。 如果我嘗試使用F5刷新頁面,圖像會被重新調整大小! 如果我嘗試Ctrl + F5,圖像會以原始尺寸返回!

問題在哪裏?爲什麼這個JavaScript只適用於頁面刷新?

+1

如果你使用'$(「 detailImg」)。負載(函數(){...'會發生什麼事?我懷疑你的腳本運行時,你的圖像不加載,因此寬度()和高度()不能被正確的確定(如果這是問題,你可能需要做更多的工作,因爲'load()'可能不會觸發緩存的圖像。請參閱http://stackoverflow.com/questions/ 910727/jQuery的事件對圖像加載) –

+1

我記得,'$(文檔)時DOM是準備就緒,圖像不能在這一點上加載.ready'觸發。嘗試'$(窗口).load' –

回答

6

您的圖片沒有加載你的document.ready()運行時。 document.ready()發生在DOM負載上,但是在那個時候圖像可能仍然在加載 - 特別是如果它們是5MB的話!因此,圖像高度和寬度在腳本運行時不可用。我猜想它的工作原理是F5,因爲圖像仍然被緩存,所以加載速度足夠快,以便在腳本運行時知道它們的尺寸。 按Ctrl - F5清除圖像緩存,因此在這之後,你回到開始的地方。

正如我在我的評論指出,使用load()事件中的圖像可以幫助,但即使這樣,有時沒有正確觸發。例如,某些瀏覽器將永遠不會爲已存在於瀏覽器緩存中的圖像觸發load()事件(因爲在技術上它尚未加載...)

有幾種不同的解決方法可以完成這一輪 - Paul Irish's plugin可能會有用;包括插件代碼,然後使用類似:

$('.detailImg',this).imagesLoaded(function() { 
    // Your existing function code 
}); 

另外,如果你事先知道圖像的大小,只需指定它在你的img元素,例如<img src="whatever" height="1200" width="1600" alt="whatever" />。這樣jQuery將能夠告訴寬度和高度圖像是否加載。

+0

就是這樣,給'IMG'標籤添加'height'和'width'!Thx! – danyolgiax

-1

把你的JS代碼放在「body close tag」之前。

希望這會有所幫助。