最初の投稿。私は同じような質問を高低で検索し、手ぶらで出てきたので、ここに行きます。
私は現在、画像カルーセルに表示するために画像のコレクションを比例的にスケーリングするために少しのjQueryを使用しています(このコードの多くをSOユーザーに感謝します)。カルーセルは、jCarousel Liteプラグイン(ここ)を利用しています。ナビゲーションメニューを使用して選択された4つの異なる画像セットがあります。新しい画像セットが選択されると、次のjQueryサイズ変更コードがセット内の各画像に対して実行され、画像カルーセルは#sliderdiv内の新しくサイズ変更された画像を使用して初期化されます。
問題:このコードは、一見ランダムに見える場合にのみ機能します。スライダーが初期化されるときに、画像が正常に拡大縮小されない場合、すべての幅が最大幅に拡大され、画像の下部がトリミングされます。この問題は、スライダーが横向きの画像(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