我在 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,我发现该函数根本没有触发。
谁能指出我为什么这可能行不通的正确方向?