You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jQuery检测单个div内所有图片加载完成后执行操作?

实现每个图片容器内所有图片加载完成后执行特定操作

原生JavaScript方案(简洁现代)

利用Promise.all批量监听图片加载状态,无需依赖第三方库,代码清晰易维护:

// 获取所有图片容器
const imgContainers = document.querySelectorAll('.imgs');

imgContainers.forEach(container => {
  const imgs = container.querySelectorAll('img');
  // 将每个图片的加载状态转为Promise
  const loadPromises = Array.from(imgs).map(img => {
    // 图片已缓存完成,直接返回已resolve的Promise
    if (img.complete) return Promise.resolve();
    // 未加载的图片,监听load/error事件(error可选,根据需求决定是否视为"完成")
    return new Promise(resolve => {
      img.addEventListener('load', resolve);
      img.addEventListener('error', resolve);
    });
  });

  // 等待当前容器内所有图片加载完成
  Promise.all(loadPromises).then(() => {
    // 这里编写当前容器的特定操作
    console.log(`容器内所有图片加载完成`, container);
    container.classList.add('imgs-loaded'); // 示例:添加加载完成类
  });
});

jQuery方案(适合已有jQuery项目)

通过计数监听图片加载事件,兼容传统项目场景:

$('.imgs').each(function() {
  const $container = $(this);
  const $imgs = $container.find('img');
  const totalImgs = $imgs.length;
  let loadedCount = 0;

  // 容器内无图片时直接执行操作
  if (totalImgs === 0) {
    handleLoaded($container);
    return;
  }

  // 监听图片加载/错误事件
  $imgs.on('load error', function() {
    loadedCount++;
    if (loadedCount === totalImgs) {
      handleLoaded($container);
    }
  });

  // 触发已缓存图片的load事件
  $imgs.each(function() {
    if (this.complete) $(this).trigger('load');
  });
});

// 定义容器加载完成后的操作
function handleLoaded($container) {
  console.log(`容器内所有图片加载完成`, $container[0]);
  $container.addClass('imgs-loaded');
}

关键注意点

  • 缓存处理:必须检查图片的complete属性,避免已缓存图片无法触发load事件导致操作不执行
  • 错误处理:如果需要仅在图片全部加载成功时执行操作,可移除error事件监听,或在Promise中reject错误并通过Promise.allSettled替代Promise.all做后续处理
  • 空容器兼容:对不含图片的容器直接执行操作,避免无意义的等待

内容的提问来源于stack exchange,提问作者SamTest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 15:30:14