내 jQuery 이미지 크기 조정 코드 만 간헐적으로 작동하는 이유는 무엇입니까?
-
12-12-2019 - |
문제
첫 번째 게시물. 비슷한 질문에 대해 높고 낮게 수색했으며 빈 손으로 빈번하게 왔으므로 여기가 간다.
현재 작은 jQuery를 사용하고 있기 위해 이미지 회전 목마에 디스플레이 할 이미지 모음을 비례 적으로 스케일링하고 있습니다 (이 코드의 대부분을 위해 사용자에게 사용자 덕분에). 회전 목마는 JCarousel Lite Plugin ( ")에 의해 제공됩니다. 탐색 메뉴를 사용하여 선택한 4 가지 이미지 세트가 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
해결책
Window Load jQuery(window).load(function() {
에서 실행하려고 시도했습니다.
이렇게하면 모든 이미지가 치수를 확인하기 전에 사용할 수 있는지 확인합니다.