【发布时间】:2013-10-03 16:00:14
【问题描述】:
我在 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,我发现这个函数根本没有触发。
谁能指出我正确的方向,为什么这可能行不通?
【问题讨论】:
-
将脚本保留在页面底部。就在
</body>标签上方
标签: javascript jquery html