简体   繁体   English

加载所有图像后执行代码

[英]Execute code after all images are loaded

I want to do some interface fixes after all images are loaded (need the heights of the elements that hold images and use them to change the heights of other elements) I attach load event to all images but my load function is executed only once. 我想在所有图像加载后进行一些接口修复(需要保留图像的元素的高度,并使用它们更改其他元素的高度),我将load事件附加到所有图像,但是我的加载功能仅执行一次。 I've try to use only jQuery: 我尝试仅使用jQuery:

$(function() {
    var $img = $('img');
    var length = $img.length;
    var count = 0;

    function load() {
       console.log(++count + ' == ' + length);
       if (count == length) {
          // all images loaded
       }
    }
    $img.load(load).error(load);
});

I also try to use onload and onerror events: 我也尝试使用onload和onerror事件:

$img.each(function() {
    this.onload = load;
    this.onerror = load;
});

but when page is loaded I've got just one log: 但是当页面加载时,我只有一个日志:

1 == 33

(I'm testing in Chromium on Xubuntu with Dev Tools and cache disabled) (我正在开发工具和禁用缓存的情况下在Xubuntu上的Chromium中进行测试)

What I've doing wrong here? 我在这里做错了什么? How to execute code after all images are loaded? 加载所有图像后如何执行代码?

Sounds like you should be handling on the window 's load event: 听起来您应该处理windowload事件:

$( window ).load(function() {
// Glorious code!!
}

From the docs: "Run a function when the page is fully loaded including graphics." 从文档中:“当页面完全加载包括图形时运行功能。”

http://api.jquery.com/load-event/ http://api.jquery.com/load-event/

Execute the function when the page has finished loading 页面加载完成后执行功能

$(window).load

That way all elements are in place and ready to be 'measured' 这样,所有要素均已准备就绪,可以“衡量”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM