用于图像调整大小的javascript在IE中不起作用?

时间:2013-02-26 07:23:29

标签: javascript jquery

下面给出的代码将图像大小调整为160x160,适用于Firefox& Chrome但不适用于Internet Explorer。为什么呢?

$(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 个答案:

答案 0 :(得分:4)

您不是在等待加载图片,因此不保证它们的大小(取决于它们是否被缓存)。

你应该替换

$(document).ready(function() {

$(document).load(function() {

这就是说,看起来你可以用这种风格取代整体:

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

(见demonstration