为什么我的jQuery图像调整大小代码只能间歇性地工作?

问题描述:

第一篇文章。我搜索了高和低的类似问题,并已空手而来,所以在这里。为什么我的jQuery图像调整大小代码只能间歇性地工作?

我目前正在使用一点点jQuery按比例缩放图像集合以在图像旋转木马中显示(感谢SO用户的大部分代码)。传送带由jCarousel Lite插件(here)供电。我有4个不同的图像集,使用导航菜单进行选择。当选择一个新的图像集时,以下jQuery调整大小代码将在该集合中的每个图像上执行,然后使用#slider div中新调整大小的图像初始化图像轮播。

问题:此代码仅在有时似乎有效,看似随机。当滑块初始化时,如果图像未成功缩放,所有宽度将增加到最大宽度,从而裁剪图像的底部。对于面向肖像的图像,这个问题尤其明显,因为滑块是针对横向图像(900px x 600px)而成形的。无论顺序或点击次数,窗口大小还是浏览器,我都无法确定导致代码成功或失败的原因。

任何想法为什么这段代码会随机执行成功?

//The following scales images proportionally to fit within the #slider div 
$('#slider ul li img').each(function() { 
    var maxWidth = $('#slider').outerWidth(false); // Max width for the image 
    var maxHeight = $('#slider').outerHeight(false); // 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; // 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 
} 

var width = $(this).width(); // Current image width 
var height = $(this).height(); // Current image height 

// Check if current height is larger than max 
if(height > maxHeight){ 
    ratio = maxHeight/height; // 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 
} 
}); 
initialize(); //initializes the jCarousel Lite carousel 

你试过在窗口负荷运行它jQuery(window).load(function() {

这将有助于确保所有的图像在一个点上检查它们的尺寸

+0

这是一个问题,我之前是可用的。我选择使用imageLoaded jQuery插件(https://gist.github.com/268257),我从中调用initialize()。 – toads

+0

几个小时后,它在我的脑海中点击了我的尺寸检查代码没有在imagesLoaded函数中执行。移动它,并且它每次都有效。谢谢! – toads