先检查图片是否加载成功,然后如果失败的话再绑定事件。而且替换一次就好了。
<img src="xxxx.jpg" alt="" />
<script>
jQuery(document).ready(function(){
jQuery('img').each(function(){
var error = false;
if (!this.complete) {
error = true;
}
if (typeof this.naturalWidth != "undefined" && this.naturalWidth == 0) {
error = true;
}
if(error){
$(this).bind('error.replaceSrc',function(){
this.src = "default_image_here.png";
$(this).unbind('error.replaceSrc');
}).trigger('load');
}
});
});
</script>
接下来这个我测试过很有效果的:
$(window).load(function() {
$('img').each(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
this.src = 'http://www.tranism.com/weblog/images/broken.gif';
}
});
});
但是IE6的时候会出现不兼容的情况所以,最好的方法是在每个标签上增加 onerror = "this.src='/cqabc/images/huancun.gif'"属性。
本文介绍了如何在网页中优化图片加载过程,并提供了在不同浏览器环境下处理图片加载失败的方法,包括使用JavaScript事件绑定和属性设置来确保用户体验。
2119

被折叠的 条评论
为什么被折叠?



