仅在图像已加载后执行图像分析

Perform image analysis only after images are already loaded

我正在寻找一种为移动设备缩放网页图像的方法。我的做法是使用JavaScript存储每张图片的尺寸,如果用户的屏幕小于某个值,所有图片将使用JavaScript调整大小。我的问题是以下函数不会检测图像是否已经加载,因此对于未加载的图像,结果将为 0。我的问题是,如何实现检查,以便函数仅在图像完全加载后才计算图像大小?我没有使用 jQuery.

function storeImageSizes() {
  isizes = [];
  imgs = document.getElementById('content').getElementsByTagName('img');
  for (var i = 0; i < imgs.length; i++) {
    isizes[i] = [
      window.getComputedStyle(imgs[i]).getPropertyValue('width').replace('px', '') * 1,
      window.getComputedStyle(imgs[i]).getPropertyValue('height').replace('px', '') * 1
    ];
  }
}

添加一个在所有 DOM 元素加载时调用的侦听器。即:

document.addEventListener("load", (function(){
   isizes = [];
  imgs = document.getElementById('content').getElementsByTagName('img');
  for (var i = 0; i < imgs.length; i++) {
    isizes[i] = [
      window.getComputedStyle(imgs[i]).getPropertyValue('width').replace('px', '') * 1,
      window.getComputedStyle(imgs[i]).getPropertyValue('height').replace('px', '') * 1
    ];
  }
})

在 window.load 函数中调用 storeImageSizes() 应该可以解决问题

$( window ).on( "load", function() { ... })

它基本上是一个事件,在加载所有图像和整个页面时触发。由于您希望函数在所有图像都加载后 运行,因此您应该使用此事件。

注意document.ready和window.load的区别。 document.ready 运行s 当 DOM 准备就绪时 window.load 运行s 一旦加载完整页面即 images/iframes 等

参考这里Simple example using Jquery

您可以使用以下解决方案在图像已加载后执行图像分析:

document.querySelector('#image').addEventListener('load', storeImageSizes);

你试过了吗image.onload
另外,检查 this answer。它突出了 image.onload 的使用,也避免了浏览器缓存问题。