コンテナーの縦横比を一連の画像の縦横比と比較し、クラスのポートレートまたはランドスケープを画像に追加しようとしています。また、定義された許容範囲に基づいて、非常に高い/広い画像 (大きなパノラマなど) を検出しようとしています。ここで基本的な機能が動作しています(最初の 2 つの画像には、左上隅に「ズーム」ボタンがあります)。
今、私は関数を分割しようとしているので、ページのサイズを変更すると、スクリプトはすべての画像の比率 (var i_ratio) を再度計算するのではなく、これらを新しいコンテナーの比率 (var c_ratio) と比較するだけです。私の開発例はこちらです。
私の問題は、次の方法がわからないことだと思います。
- 最初の関数が完了した後に 2 番目の関数が実行されるようにする
- 最初の関数の i_ratio の値を次の関数に渡します
開発者の例では、i_ratio が 2 番目の関数内で定義されていないことを示すコンソール ログがありますが、ウィンドウのサイズを変更すると、値を取得するように見えます - 何が起こっているのかわかりません。
// Get window aspect ratio
var container = $('.main');
var c_ratio = container.width() / container.height();
var i_ratio;
function imageRatios() {
// Get original dimensions of image (IE8+)
if (this.naturalWidth) {
i_width = this.naturalWidth;
i_height = this.naturalHeight;
} else {
// Get original dimensions of image with JQuery
i_width = this.width;
i_height = this.height;
}
i_ratio = i_width / i_height;
// Don't allow images to get bigger than their original size
$(this).css('max-width', i_width).css('max-height', i_height);
}
function setClass() {
console.log('number of images: '+images.length+', i_ratio from imageRatios function: '+i_ratio);
// Add ratio classes
if (c_ratio > i_ratio) {
$(this).parent('li').removeClass('landscape').addClass('portrait');
} else {
$(this).parent('li').removeClass('portrait').addClass('landscape');
}
// Identify long/tall panoramas and add zoom button
tolerance = c_ratio / i_ratio;
if (tolerance < 0.3 || tolerance > 5) {
$(this).after('<div class="zoom"></div>');
} else {
$(this).remove('.zoom');
}
// Show/hide zoomed image
var img = $(this);
$(this).next('.zoom').click(function() {
if (img.siblings('.big_image').size() > 0) {
$('.big_image').remove();
} else {
$(this).after('<div class="big_image"><img src="'+$img.attr('src')+'"></div>');
}
});
}
// Get images
var images = $('.main img');
images.each(function(i) {
if (this.complete) {
imageRatios.call(this);
setClass();
} else {
this.onload = imageRatios;
setClass();
}
});
// Update ratio class on resize
$(window).on("throttledresize", function() {
var c_ratio = container.width() / container.height();
images.each(function() {
setClass();
});
});