利用 jQuery `animate()` 實現鼠標懸停顯示、移開隱藏的平滑過渡效果,結合遮罩層(Overlay)構建 Loading 狀態指示器。本文提供 CSS 布局、JS 初始化/顯示/隱藏函數、AJAX 整合調用完整代碼,並解析關鍵動畫參數與層級管理。
/* 遮罩層:固定全屏,半透明背景,初始隱藏 */
.overlay {
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
z-index: 998; background: #f6f4f5; display: none; opacity: 0;
}
/* 內容框:居中顯示,初始透明偏上 */
.showbox {
position: fixed; top: 0; left: 50%; z-index: 9999;
opacity: 0; filter: alpha(opacity=0); margin-left: -80px; /* 寬度一半 */
}
/* Loading 文本區域 */
#AjaxLoading { border: 1px solid #8CBEDA; color: #37a; font-weight: bold; }
#AjaxLoading .loadingWord { width: 180px; height: 50px; line-height: 50px; border: 2px solid #D6E7F2; background: #fff; }
#AjaxLoading img { margin: 10px 15px; float: left; display: inline; }
/* IE6 兼容(可省略) */
* html .showbox, * html .overlay { position: absolute; top: expression(eval(document.documentElement.scrollTop)); }
var Util = { getContentPath: function() { return ''; } }; // 適配項目路徑
function getLoadingHtml(msg) {
msg = msg || '加載';
return "<div id='loadingDiv'>" +
"<div class='overlay' style='height:1325px; display:none; opacity:0'></div>" +
"<div id='AjaxLoading' class='showbox' style='opacity:0; margin-top:250px'>" +
"<div class='loadingWord'><img src='" + Util.getContentPath() + "/images/ajax-loader.gif'>" + msg + "中,請稍候...</div>" +
"</div><div style='height:1200px'></div></div>";
}
function ajaxLoadingInit(msg) {
var h = $(document).height();
$('.overlay').css('height', h);
$('#loadingDiv').remove();
$('body').append(getLoadingHtml(msg));
}
function startLoading(msg) {
ajaxLoadingInit(msg);
$('.overlay').css({display: 'block', opacity: '0.8'}); // 直接顯示遮罩
$('.showbox').stop(true).animate({marginTop: '300px', opacity: '1'}, 200); // 下滑淡入
}
function endLoading() {
$('.showbox').stop(true).animate({marginTop: '250px', opacity: '0'}, 400); // 上滑淡出
$('.overlay').css({display: 'none', opacity: '0'}); // 直接隱藏遮罩
}
| 參數 | 顯示動畫 | 隱藏動畫 | 作用 |
|---|---|---|---|
| marginTop | 250px → 300px | 300px → 250px | 垂直位移產生「彈出/收回」感 |
| opacity | 0 → 1 | 1 → 0 | 淡入/淡出 |
| duration | 200ms | 400ms | 隱藏稍慢,視覺更自然 |
| .stop(true) | 清空動畫隊列,跳到當前動畫末幀,防疊加 | ||