在進行 Ajax 提交時,加入等待動畫能提升使用者體驗,讓使用者知道系統正在處理。本文封裝了一個通用的 Loading 動畫方法,方便在多處重複使用。
程式碼如下:
/*ajax提交的延時等待效果*/
var AjaxLoding = new Object();
//lodingid : 顯示loding圖片的容器元素
//ms:表示loding圖標顯示的時長,毫秒
//event:表示觸發事件的事件源對象
//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;
this.obj = $("#" + this.lodingid);
this.sourceEventElement=$(event.currentTarget);
this.start = function () {
this.obj.css({positin:"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);
this.obj.animate({height:this.obj.height()}, ms, function () {
callback();
});
};
this.stop = function () {
$("#img_loding").remove();
this.sourceEventElement.attr("disabled", false);
}
};呼叫方式:
$("#elementid").click(function (e) {
var obj = new AjaxLoding.load("div_test", 2000,e,0,0,function () {
//alert("提交成功!");
obj.stop();//隱藏加載圖標
});
obj.start();
});使用時只需指定容器 id、動畫時長、事件來源與回調函式即可。呼叫 stop() 會移除圖示並恢復觸發元素的可用狀態,形成完整的等待流程。