DIV CSS 佈局教程網

依頁面載入狀態顯示遮罩與 Loading 動畫
編輯:關於JavaScript     

頁面資源多、載入慢的時候,讓使用者盯著半白的畫面乾等是最糟的體驗。加一層遮罩與轉圈動畫,就能明確告知「正在載入」,同時避免誤點擊。

完整實作

function initialize() {
    addcloud();                              // 加上遮罩
    document.onreadystatechange = subSomething;   // 監聽載入狀態
}

function addcloud() {
    var bodyWidth = document.documentElement.clientWidth;
    var bodyHeight = Math.max(document.documentElement.clientHeight,
                              document.body.scrollHeight);

    // 遮罩層
    var bgObj = document.createElement("div");
    bgObj.setAttribute('id', 'bgDiv');
    bgObj.style.position = "absolute";
    bgObj.style.top = "0";
    bgObj.style.left = "0";
    bgObj.style.background = "#000000";
    bgObj.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=3,opacity=25,finishOpacity=75)";
    bgObj.style.opacity = "0.5";
    bgObj.style.width = bodyWidth + "px";
    bgObj.style.height = bodyHeight + "px";
    bgObj.style.zIndex = "10000";   // 墊在最上層,攔住所有點擊
    document.body.appendChild(bgObj);

    // Loading 動畫
    var loadingObj = document.createElement("div");
    loadingObj.setAttribute('id', 'loadingDiv');
    loadingObj.style.position = "absolute";
    loadingObj.style.top = bodyHeight / 2 - 32 + "px";
    loadingObj.style.left = bodyWidth / 2 + "px";
    loadingObj.style.background = "url(../img/loading.gif)";
    loadingObj.style.width = "32px";
    loadingObj.style.height = "32px";
    loadingObj.style.zIndex = "10000";
    document.body.appendChild(loadingObj);
}

function removecloud() {
    $("#loadingDiv").remove();
    $("#bgDiv").remove();
}

function subSomething() {
    if (document.readyState == "complete") {   // 載入完畢,移除遮罩
        removecloud();
    }
}

幾個關鍵細節

  • z-index 墊高:遮罩層必須高於頁面所有元素,才能真正攔住使用者的誤觸。
  • 高度取最大值:用 Math.max(clientHeight, scrollHeight) 確保內容超出視窗時遮罩仍能蓋滿整頁。
  • 透明度雙寫:filter 給舊 IE,opacity 給標準瀏覽器。
  • readyState 的變化:document.onreadystatechange 會依序經歷 loading → interactive → complete,因此這個回呼也能用來在其他階段插入不同邏輯。

現代寫法

如果不必支援舊 IE,直接用 CSS 就能取代大半程式碼:

.mask {
    position: fixed; inset: 0;
    background: rgba(0,0,0,.5);
    z-index: 10000;
}

再搭配 window.addEventListener('load', ...) 移除節點即可,程式碼量大幅縮減,也免去了手動計算寬高的麻煩。

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