javascript - 为什么即使没有 src 标签,图像 'complete' 属性也总是返回 true?

标签 javascript html image internet-explorer-11

我只是写

document.createElement("img").complete;//To check whether image is loaded or not

在 Firefox 中,它返回 true。在IE中返回false

在 html 页面中,只需创建一个图像:

 <!-- IMG tag with no SRC attribute. -->
<img id="noSrcImg" />

并在 js 中检查完整的属性值:

var img = document.getElementById("noSrcImg");
img.complete

对于 FF 为真,对于 IE 为假

谁能解释为什么会出现这种不一致的行为?

有没有其他更好的方法来检查 DOM 中是否加载了图像?

我也尝试使用 readyState 属性,但它不适用于 IE11。

最佳答案

这是 IE 中的错误。 According to the spec :

The IDL attribute complete must return true if any of the following conditions is true:

  • The src attribute is omitted.
  • The final task that is queued by the networking task source once the resource has been fetched has been queued.
  • The img element is completely available.
  • The img element is broken.

Otherwise, the attribute must return false.

了解图像状态的最佳方法是处理loaderror 事件。如果这不可行,无论出于何种原因,要判断图像是否已成功加载,请检查 img.complete && img.naturalWidth > 0。如果为真,则图像已成功加载。否则,图像要么仍在加载,要么加载失败 - 由于 IE 的不一致,很难分辨是哪一个。

关于javascript - 为什么即使没有 src 标签,图像 'complete' 属性也总是返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23657424/

相关文章:

image - Photoshop 中曝光调整中的偏移 slider 背后的数学原理是什么?

javascript - 围绕箭头主体的意外 block 语句 ESlint

javascript - 使用 Chromeless Player 适度打造品牌

javascript - 如何遍历到具有特定类的下一个dom元素?

javascript - 根据浏览器滚动条的位置缩放 div 的大小

php - 使用sql INSERT将日期输入mysql数据库

javascript - 使用助手渲染 Ember View

javascript - 仅允许文本字段中的特定数字

HTML CSS 背景图像保持宽度与浏览器宽度相同

image - 如何判断图像是否为 90% 黑色?