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

前端之家收集整理的这篇文章主要介绍了jquery回调在dom中的所有图像加载?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在DOM中的所有图片加载时触发事件?
我已经google了很多。我发现这个,但它似乎不工作:

jQuery event for images loaded

解决方法

对窗口使用 load()(docs)方法
  1. $(window).load(function() {
  2. // this will fire after the entire page is loaded,including images
  3. });

或者直接通过window.onload

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

如果您想要为每个图像触发单独的事件,请在每个图像上放置一个.load()。

  1. $(function() {
  2. $('img').one('load',function() {
  3. // fire when image loads
  4. });
  5. });

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

  1. $(function() {
  2. function imageLoaded() {
  3. // function to invoke for loaded image
  4. }
  5. $('img').each(function() {
  6. if( this.complete ) {
  7. imageLoaded.call( this );
  8. } else {
  9. $(this).one('load',imageLoaded);
  10. }
  11. });
  12. });

编辑:

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

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

  1. $(function() {
  2. function imageLoaded() {
  3. // function to invoke for loaded image
  4. // decrement the counter
  5. counter--;
  6. if( counter === 0 ) {
  7. // counter is 0 which means the last
  8. // one loaded,so do something else
  9. }
  10. }
  11. var images = $('img');
  12. var counter = images.length; // initialize the counter
  13.  
  14. images.each(function() {
  15. if( this.complete ) {
  16. imageLoaded.call( this );
  17. } else {
  18. $(this).one('load',imageLoaded);
  19. }
  20. });
  21. });

猜你在找的jQuery相关文章