尽量为webAPI,或者第三方库的API
<div class="imgdv">
<img src="1.jpg" >
<img src="2.jpg" >
<img src="3.jpg" >
</div>
$('img').onload = function() {
//code
}
$(function () {
$(".imgdv").each(function() {
var img = $(this);
img.load(function () {
img.attr("isLoad", "true");
});
img.error(function() {
});
});
});
<img>
元素在 JS 中对应 HTMLImageElement
接口,含有一个 complete
属性,表示该图片元素是否完成加载。不论是图片 error 了还是成功显示了都为 true
。
结合同接口的 naturalWidth
、naturalHeight
属性可以判断图片是否成功展示。这两个属性在图片未加载或加载失败时同为 0 。一般来说只要结合一个是否为 0 就好了。
结合 <picture>
和 <source>
元素加载的图片也只需要读取对应的 <img>
元素上述属性就可以了。
... the source element's src attribute has no meaning when the element is nested within a picture element, ... the picture element itself does not display anything; it merely provides a context for its contained img element that enables it to choose from multiple URLs.
—— Note in The picture element | HTML Standard
对于从 <object>
载入的图片则没有上述等价属性可以使用。如果该 <object>
元素有子节点,可以根据 <object>
元素仅在加载目标对象失败时显示子节点的特性,以类似于 .firstElementChild.offsetParent
是否为 null
这样的方式判断图片是否加载失败。
更常见更精细的判断需要通过事件侦听实现。
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答1.4k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
图片有个 onload 事件,触发就表示图片已加载。
还有个 onerror 事件,触发就代表图片加载失败,一般会在 onerror 事件里面补一个错误图片。