dom中所有图像加载后jquery回调?

标签 jquery image load

加载 DOM 中的所有图像后如何触发事件? 我用谷歌搜索了很多。我发现了这个,但似乎不起作用:

jQuery event for images loaded

最佳答案

使用load()(docs)针对窗口的方法。

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

注意:在较新的 jQuery 版本上使用 $(window).on('load', function(){ ...});

或者直接通过 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
    });
});

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

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

编辑:

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

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

$(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回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4857896/

相关文章:

javascript - 地理图表上关闭工具提示按钮的工作版本代码?

javascript - 使用nodejs在mongodb中添加另一个图像路径

image - 如何将单 channel IplImage* 转换为位图^

python - TensorFlow 2.0 C++ - 加载预训练模型

javascript - 立即加载函数 - 无法访问 <body>

jquery 验证 onchange

javascript - 如何突出显示未通过 Struts2 验证的字段?

Objective-C 保存和加载文件

javascript - 如何通过测试 event.which == 13 来关注下一个字段,而不在当前字段中留下尾随\n?

Java Swing - 如何在Jpanel的北部添加图像