2011-08-11 69 views
1

现在我正在尝试下面的代码。这在大多数情况下都是有效的(在第一次访问后重新加载时),但是当第一次访问页面时,图像没有正确调整大小。 我认为这是因为图像在页面就绪回调被触发之前加载。如何将图像限制为最大宽度/高度?

我已经尝试直接在.ready()回调中调用.resize()函数,但图像仍然不会调整大小,因为图像可能在触发.ready()回调时加载。

我应该如何去连接resize()函数来让图像正确调整大小,而不管何时加载?

function resize($img) { 
    var max_size_w = 200; 
    var max_size_h = 200; 
    var h = $img.height(); 
    var w = $img.width(); 
    if (h > max_size_h) { 
     h = max_size_h; 
     w = Math.ceil($img.width()/$img.height() * max_size_h); 
    } 
    if (w > max_size_w) { 
     h = Math.ceil($img.height()/$img.width() * max_size_w); 
     w = max_size_w; 
    } 
    $img.css({ height: h, width: w }); 
} 

$().ready(function() { 
    // Size the images correctly 
    $(".personPictureImage").each(function() { 
     $(this).find("img").load(function() { resize($(this)); }); 
    }); 
}); 

UPDATE:的HTML

<div class="personPicture"> 
    <div class="personPictureFrame"> 
     <div class="personPictureImage"> 
      <a href="../images/media/popup/46.png" class="lightbox"> 
       <img src="../images/media/thumbnail/46.png" alt=""> 
      </a> 
     </div> 
     <div class="personPictureFrameTL"></div> 
     <div class="personPictureFrameTR"></div> 
     <div class="personPictureFrameBL"></div> 
     <div class="personPictureFrameBR"></div> 
    </div> 
</div> 
+0

可以显示我们的HTML结构?什么是.personPictureImage? –

+1

是否有你不使用CSS的原因? - .personPictureImage img {max-width:200px;最大高度:200像素; } – udjamaflip

+0

@udjamaflip - 在大多数IE版本中不起作用 – Justin808

回答

1

将调用功能的窗口加载函数内后,所有的图像来调整已加载:

$(window).load(function(){ 
    // Size the images correctly 
    $(".personPictureImage").each(function() { 
     resize($(this)); 
    }); 
}); 

而且使用$().ready已被弃用,使用$(function(){$(document).ready(function(){

+0

您能否将我指向文档并弃用? – Justin808

+0

http://api.jquery.com/ready/ - 我猜这是“被”弃用......它确实说不建议使用。 – Mottie

0
$(document).ready(function(){ 
function resize($img) { 
    var max_size_w = 200; 
    var max_size_h = 200; 
    var h = $img.height(); 
    var w = $img.width(); 
    if (h > max_size_h) { 
     h = max_size_h; 
     w = Math.ceil($img.width()/$img.height() * max_size_h); 
    } 
    if (w > max_size_w) { 
     h = Math.ceil($img.height()/$img.width() * max_size_w); 
     w = max_size_w; 
    } 
    $img.css({ height: h, width: w }); 
    } 

    $(".personPictureImage").each(function() { 
     $(this).find("img").load(function() { resize($(this)); }); 
    }); 

}()) 

这应该工作。

+0

这看起来只是将调整大小功能移入就绪回调。这是如何解决时间问题的(例如,图像是在调用ready回调之前加载的)? – Justin808

相关问题