页面图片加载等候以及加载失败后图片替换

本文介绍了一个使用jQuery实现的图片加载插件,该插件能够处理图片加载等待以及加载失败后的替换操作。通过自定义选项,用户可以设置加载提示、默认图片及超时时间,确保网站的图片加载体验更加流畅。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


/*
* jQuery loadImage plugin
* Version 2.0.0-2014.11.03
* Requires jQuery v1.7 or later
*
* @Description: 页面图片加载等候以及加载失败后图片替换
* @Author:
* @CreateDate:
* @UpdateDate: 2014-11-03 14:15:00
*/
(function($){
// plugin definition
$.fn.LoadingImg = function(options) {
// Extend our default options with those provided.
// Note that the first arg to extend is an empty object -
// this is to keep from overriding our "defaults" object.
var opts = $.extend({}, $.fn.LoadingImg.defaults, options);
// Our plugin implementation code goes here.
return this.each(function(){
var that = this;
var src = $(this).attr(opts.imgUrl); //获取当前的imgUrl属性
var img = new Image(); //建立新图片
img.src = src;
// 图片加载失败后替换相应位置为默认图片
$(img).error(function(){
loading.remove();
$(that).attr("src", opts.defaultImg);
$(that).show();
});
var loading = $(opts.loading);
$(this).hide(); //隐藏当前图片
$(this).after(loading); //添加loading图片
// 图片加载完成以后,替换页面对应位置图片的src属性为加载完成的图片
$(img).load(function() { //当前图片下载完毕后
loading.remove();
//clearTimeout(timeout);
$(that).attr("src", src);
$(that).show();
});

/*
var timeout = setTimeout(function() {
loading.remove();
$(that).attr("src", opts.defaultImg);
$(that).show();
}, opts.outTime);
*/
});
};
// plugin defaults - added as a property on our plugin function
$.fn.LoadingImg.defaults = {
loading: "<img alt=\"加载中...\" class=\"financingItemPic hover_transition hover_fade\" title=\"图片加载中...\" src=\"images/image_loading.gif\" />",
defaultImg: 'images/theforecast.jpg',
imgUrl: "imgUrl",
//outTime: 5000,
onLoaded: false
};
})(jQuery);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值