在dom中的所有图像加载后jquery回调? [英] jquery callback after all images in dom are loaded?

查看:116
本文介绍了在dom中的所有图像加载后jquery回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在加载DOM中的所有图像时如何触发事件?
我用Google搜索了很多东西。我发现了这个,但它似乎不起作用:

How can I fire an event when all images in the DOM are loaded? I've googled a lot. I've found this, but it doesn't seem to work:

加载图片的jQuery事件

推荐答案

使用 负载() (文档) 针对窗口的方法

$(window).load(function() {
    // this will fire after the entire page is loaded, including images
});

或者直接通过 window.onload

Or just do it directly via window.onload .

window.onload = function() {
    // this will fire after the entire page is loaded, including images
};






如果您想要为每个事件单独触发事件图片,在每张图片上放置 .load()

$(function() {
    $('img').one('load',function() {
        // fire when image loads
    });
});

或者,如果有可能缓存图像,请执行以下操作:

Or if there's a chance an image may be cached, do this:

$(function() {
    function imageLoaded() {
       // function to invoke for loaded image
    }
    $('img').each(function() {
        if( this.complete ) {
            imageLoaded.call( this );
        } else {
            $(this).one('load', imageLoaded);
        }
    });
});






编辑:

为了在最后一次图像加载后执行某些操作,请使用计数器设置总图像数,并在每次调用加载处理程序时递减。

In order to perform some action after the last image loads, use a counter set at the total number of images, and decrement each time a load handler is called.

当它达到 0 时,运行一些其他代码。

When it reaches 0, run some other code.

$(function() {
    function imageLoaded() {
       // function to invoke for loaded image
       // decrement the counter
       counter--; 
       if( counter === 0 ) {
           // counter is 0 which means the last
           //    one loaded, so do something else
       }
    }
    var images = $('img');
    var counter = images.length;  // initialize the counter

    images.each(function() {
        if( this.complete ) {
            imageLoaded.call( this );
        } else {
            $(this).one('load', imageLoaded);
        }
    });
});

这篇关于在dom中的所有图像加载后jquery回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆