jQuery(document).ready() と jQuery(window).load() で関数を起動します。どちらも同じ機能です。画像のサイズ変更スクリプトを起動することになっています。
ただし、サーバーの応答が遅いと、ページの読み込みが完了したときにスクリプトがまったく起動しないことがあります。
私はかなり長い間この問題を抱えていました。おそらくやり過ぎかもしれませんが、今では、ドキュメントの準備とウィンドウの読み込みの両方で、以下に示すように関数を呼び出しています。
jQuery('img', '.background').each(function(){
jQuery(this).load(function(){
jQuery(this).resizeImage();
});
});
呼び出す関数は次のとおりです。
jQuery.fn.resizeImage = function() {
console.log('fired');
var bgImg = jQuery(this);
/* get img sizes */
var imgwidth = bgImg.width();
var imgheight = bgImg.height();
/* get window sizes */
var winwidth = jQuery(window).width();
var winheight = jQuery(window).height();
/* get the ratio, checks wether window is bigger or smaller than the image */
var widthratio = winwidth / imgwidth;
var heightratio = winheight / imgheight;
/* checks the difference */
var widthdiff = heightratio * imgwidth;
var heightdiff = widthratio * imgheight;
/* if you want the entire image to always fit the screen, change the > to < */
if(heightdiff>winheight) {
bgImg.css({
width: winwidth+'px',
height: heightdiff+'px',
marginLeft: '-'+winwidth/2+'px'
});
} else {
bgImg.css({
width: widthdiff+'px',
height: winheight+'px',
marginLeft: '-'+widthdiff/2+'px'
});
}
};
console.log を使用すると、関数がまったく起動しないことがわかりました。
なぜこれがうまくいかないのか、誰かが私を正しい方向に向けることができますか?