本文介绍如何使用JavaScript封装一个AjaxLoading对象,用于在AJAX提交过程中显示加载动画。通过指定容器、时长及回调函数,实现加载图标的居中显示与隐藏,并自动禁用触发元素以防止重复提交,提升用户交互体验。
AjaxLoading对象定义与参数说明
代码如下:
/* 用于Ajax提交时的延时等待效果 */
var AjaxLoding = new Object();
//wraperid : 显示loding图片的容器元素
//ms:表示loding图标显示的时长,毫秒
//envent:表示出发事件的事件源对象,用于获得出发事件的对象
//callback:表示动画结束后执行的回掉方法
//stop()方法表示在回掉方法执行成功后执行的隐藏动画的操作
AjaxLoding.load = function(lodingid,ms,event,left,top,callback){
if (!left || typeof left == undefined)
left = 0;
if (!top || typeof top == undefined)
top = 0;}
this.lodingid = lodingid; // 显示Loading图标的父元素
this.obj = $("#" + this.lodingid);
this.sourceEventElement = $(event.currentTarget);
this.start = function () {
// 设置父元素为相对定位
this.obj.css({ position: "relative" });
// 禁用触发事件的元素,防止重复点击
this.sourceEventElement.attr("disabled", true);
// 默认将图标居中显示在lodingid容器中,设置如下样式
var imgobj = $("<img src='/images/loaderc.gif' style='position:absolute; width:32px; height:32px;' id='img_loding'/>");
// 计算图标位置,使其居中并考虑偏移量
imgobj.css({
left: this.obj.width() / 2 - imgobj.width() / 2 - left,
top: this.obj.height() / 2 - imgobj.height() / 2 - top
});
// 将图标添加到容器中
imgobj.appendTo(this.obj);
// 执行动画,时长为ms,完成后执行回调
this.obj.animate({ height: this.obj.height() }, ms, function () {
callback();
});
};
this.stop = function () {
// 移除Loading图标
$("#img_loding").remove();
// 重新启用触发事件的元素
this.sourceEventElement.attr("disabled", false);
};
};Loading动画调用示例
调用方法示例:
代码如下:
$("#elementid").click(function (e) {
var obj = new AjaxLoding.load("div_test", 2000, e, 0, 0, function () {
// alert("提交成功!");
obj.stop(); // 隐藏加载图标
});
obj.start();
});
这是我使用的Loading图标,大家可以自行替换。