0

我在 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,我发现该函数根本没有触发。

谁能指出我为什么这可能行不通的正确方向?

4

2 回答 2

0

自己解决了。

问题如下:

jQuery(window).load(function(){
    jQuery('img', '.background').each(function(){
        jQuery(this).load(function(){
            jQuery(this).resizeImage();
        });
    });
});

由于双重加载(jQuery(window).load 和 jQuery(this).load),代码根本没有执行。由于加载窗口时,图像也已经加载。

于 2013-10-03T08:00:14.243 回答
0

猜你错过了使用this

   jQuery('img', '.background').each(function(){
        var $self = $(this);
        $self.load(function(){
            $self.resizeImage();
        });
    });
于 2013-10-02T16:14:54.087 回答