DIV CSS 佈局教程網

用 jQuery animate 做出載入動畫:滑入顯示、完成後淡出隱藏
編輯:JQuery特效代碼     

在送出 AJAX 請求時,給使用者一個「處理中」的載入提示是很常見的做法。這裡示範如何透過 jQuery 的 animate,做出遮罩淡入、提示框滑入,請求完成後再淡出的流暢效果。

一、CSS 樣式

@CHARSET "UTF-8";
* html .showbox,* html .overlay {
    position: absolute;
    top: expression(eval(document.documentElement.scrollTop) );
}
#AjaxLoading {
    border: 1px solid #8CBEDA;
    color: #37a;
    font-size: 12px;
    font-weight: bold;
}
#AjaxLoading div.loadingWord {
    width: 180px;
    height: 50px;
    line-height: 50px;
    border: 2px solid #D6E7F2;
    background: #fff;
}
#AjaxLoading img {
    margin: 10px 15px;
    float: left;
    display: inline;
}
.overlay {
    position: fixed;
    top: 0; right: 0; bottom: 0; left: 0;
    z-index: 998;
    width: 100%;
    height: 100%;
    _padding: 0 20px 0 0;
    background: #f6f4f5;
    display: none;
}
.showbox {
    position: fixed;
    top: 0;
    left: 50%;
    z-index: 9999;
    opacity: 0;
    filter: alpha(opacity = 0);
    margin-left: -80px;
}

二、JS 邏輯

/**
 * 加載動畫窗口
 */
function getLoadingHtml(msg) {
    if(!msg) msg = "加載";
    var html = "<div id='loadingDiv'>"
        + "<div style='height: 1325px; display: none; opacity: 0;' class='overlay'></div>"
        + "<div style='opacity: 0; margin-top: 250px;' id='AjaxLoading' class='showbox'>"
        + "<div class='loadingWord'>"
        + "<img src='" + Util.getContentPath() + "/images/ajax-loader.gif'>" + msg + "中,請稍候..."
        + "</div>"
        + "</div>"
        + "<div style='height: 1200px;'></div>"
        + "</div>";
    return html;
}
function ajaxLoadingInit(msg) {
    var loadingDiv = getLoadingHtml(msg);
    var h = $(document).height();
    $(".overlay").css({"height": h});
    var div = $("body").find("#loadingDiv");
    div.remove();
    $("body").append($(loadingDiv));
}
/**
 * 開始顯示 loading,在 ajax 執行之前調用
 */
function startLoading(msg) {
    ajaxLoadingInit(msg);
    $(".overlay").css({'display':'block','opacity':'0.8'});
    $(".showbox").stop(true).animate({'margin-top':'300px','opacity':'1'},200);
}
/**
 * 加載完成後隱藏,在 ajax 執行完成後(complete)調用
 */
function endLoading() {
    $(".showbox").stop(true).animate({'margin-top':'250px','opacity':'0'},400);
    $(".overlay").css({'display':'none','opacity':'0'});
}

三、呼叫方式

startLoading();
$.ajax({
    type : "POST",
    url : this.url,
    dataType : "json",
    data : this.args,
    success : function (data) {
    },
    complete : function () {
        if (self.showLoading == true) endLoading();
    },
    error : this.error
});

使用時只要在 $.ajax 之前呼叫 startLoading(),並在 complete 回呼裡呼叫 endLoading() 即可。遮罩高度會依目前文件高度動態調整,滑入與淡出則全靠 animate 完成,整體過渡相當平順。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved