使用默认图片替代某张图为空时的情况

今天听小伙伴在群上讨论当图片为空时使用默认图的情况,作为好奇一下,自己写了一段程序好验证一下;

在这里不得不谈ready和load的区别了:

reay先于load执行,就是在构造html,dom模型的时候执行,而load的话,则在页面加载完毕之后执行,以下是执行步骤:

1.解析HTML结构

2.加载外部脚本和样式表文件

3.解析并执行脚本代码

4.构造HTML DOM模型   //ready

5.加载图片等外部文件

6.页面加载完毕 //load

方法1:在ie下不能用,火狐体验不是很好

$(function(){

$("img").one("error",function(){//设置one防止默认图片也是空的,而导致陷入死循环
$(this).attr("src","images/01.jpg");//设置默认图片
})

})

方法2:ie,火狐,谷歌都可以用,这个方法是百度得来的ps:naturalWidth是html5判断图片width的属性,有兴趣的小伙伴可以去百度一下(涨知识了)。

$(window).load(function() {
$('img').each(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
this.src = 'images/01.jpg';
}
});


});
不过在ie8下会把所有图片替代为默认图:


方法3:测试了下,在ie8下也没有问题(当然了这个也是我去看别人的代码,修改过来的,已经过本人的苦苦测试)原文地址:https://segmentfault.com/q/1010000000120137
$(window).load(function() {
$('img').each(function(){
var error = false;
if (!this.complete) {
error = true;
}
if (typeof this.naturalWidth != "undefined" && this.naturalWidth == 0) {
error = true;
}

if(error){
this.src = "images/01.jpg";
}
});
});

后话:做前端不容易,做好兼容性更不容易


原文地址:https://www.cnblogs.com/yanzai/p/5293129.html