¿Por qué mi imagen jQuery cambia de tamaño del código solo funciona de manera intermitente?

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

Pregunta

primer post. He buscado alto y bajo para preguntas similares y he subido con las manos vacías, así que aquí va.

Actualmente estoy usando un poco de jQuery para escalar proporcionalmente una colección de imágenes para mostrar en un carrusel de imágenes (gracias a los usuarios de gran parte de este código). El carrusel está impulsado por el plugin de Jcarousel Lite ( aquí ). Tengo 4 conjuntos de imágenes diferentes, que se seleccionan utilizando un menú de navegación. Cuando se selecciona un nuevo conjunto de imágenes, el siguiente código de cambio de tamaño jQuery se ejecuta en cada imagen en el conjunto, y luego el carrusel de la imagen se inicializa utilizando las imágenes recién redactadas dentro del #slider DIV.

El problema : este código solo funciona a veces, aparentemente al azar. Cuando el control deslizante se inicializa, si las imágenes no se escalan con éxito, todos los anchos se incrementan al ancho máximo, recortando así la parte inferior de la imagen. Este problema es especialmente evidente para las imágenes orientadas al retrato, ya que el control deslizante tiene la forma de las imágenes orientadas al horizonte (900px x 600px). No puedo identificar lo que hace que el código funcione con éxito o no, independientemente del pedido o los clics, el tamaño de la ventana o el navegador.

¿Alguna idea de por qué este código se ejecutará al azar con é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

¿Fue útil?

Solución

¿Ha intentado ejecutarlo en la carga de la ventana jQuery(window).load(function() {

Esto ayudará a garantizar que todas las imágenes estén disponibles antes de revisar sus dimensiones

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top