JavaScript的图像调整大小不工作在IE浏览器?

问题描述:

下面给出的代码将图片大小调整为160x160,并且适用于Firefox & Chrome,但不适用于Internet Explorer。为什么?JavaScript的图像调整大小不工作在IE浏览器?

$(document).ready(function() { 
    $('#imagePreview img').each(function() { 
     $('#imagePreview img').each(function() { 
      var maxWidth = 160;    // Max width for the image 
      var maxHeight = 160;   // 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; 
       $(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; 
       $(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 
      } 
     }); 
    }); 
}); 
+1

为什么两个函数... – 2013-02-26 07:27:26

+0

为什么你添加了行$('#imagePreview img')。each(function(){two times in code。 – 2013-02-26 07:28:12

+1

总是提供HTML,CSS,JS相关问题和答案的演示:[JSBin](http://jsbin.com/) – 2013-02-26 07:29:25

您并未等待图像加载,因此它们不能保证具有大小(取决于它们是否被缓存)。

你应该

$(document).load(function() { 

这是说更换

$(document).ready(function() { 

,它看起来像你可以用这种风格整体更换:

#imagePreview img { 
    max-width: 160px; 
    max-height: 160px; 
} 

(见demonstration