Por que meu código de redimensionamento de imagem jQuery funciona apenas de forma intermitente?

StackOverflow https://stackoverflow.com//questions/10679000

Pergunta

Primeiro post.Pesquisei de alto a baixo por perguntas semelhantes e não encontrei de mãos vazias, então aqui vai.

Atualmente, estou usando um pouco de jQuery para dimensionar proporcionalmente uma coleção de imagens para exibição em um carrossel de imagens (graças aos usuários do SO por grande parte deste código).O carrossel é alimentado pelo plugin jCarousel Lite (aqui).Tenho 4 conjuntos de imagens diferentes, que são selecionados usando um menu de navegação.Quando um novo conjunto de imagens é selecionado, o código de redimensionamento jQuery a seguir é executado em cada imagem do conjunto e, em seguida, o carrossel de imagens é inicializado usando as imagens recém-redimensionadas na div #slider.

O problema:esse código só funciona às vezes, aparentemente de forma aleatória.Quando o controle deslizante é inicializado, se as imagens não forem dimensionadas com sucesso, todas as larguras serão aumentadas para a largura máxima, cortando assim a parte inferior da imagem.Este problema é especialmente aparente para imagens orientadas para retrato, já que o controle deslizante é moldado para imagens orientadas para paisagem (900px x 600px).Não consigo identificar o que faz com que o código funcione com êxito ou não, independentemente da ordem ou dos cliques, do tamanho da janela ou do navegador.

Alguma idéia de por que esse código seria executado aleatoriamente com êxito?

//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
Foi útil?

Solução

Você já tentou executá-lo no carregamento da janela jQuery(window).load(function() {

Isso ajudará a garantir que todas as imagens estejam disponíveis antes de verificar suas dimensões.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top