DIV CSS 佈局教程網

JS 進度條效果的幾種實作整理
編輯:關於JavaScript     

進度條在等待類操作中是基本配備。以下整理三種思路不同的實作方式,從最簡單的圖片位移,到可配置的類別封裝,再到圖片批量載入的進度追蹤。

方法一:以圖片寬度變化模擬進度

先建立 Loading.js:

// 刷新頻率(毫秒)
var frequency = 50;
// 步長(每次前進的像素)
var step = 3;
// 背景顏色
var loadingBgcolor = "#ffffff";
// 進度條寬度
var loadingWidth = 354;

/*
 * 參數說明:
 * content:顯示內容,可為空
 * imageURL:引用JS檔案的所在路徑
 * left:進度條顯示位置的 left
 * top:進度條顯示位置的 top
 */
function Loading(content, imageURL, left, top) {
    imageURL = imageURL + "Loading.jpg";
    LoadTable(content, imageURL, left, top);
    showimage.style.display = "";
    window.setInterval("RefAct();", frequency);
}

function RefAct() {
    imgAct.width += step;
    if (imgAct.width > loadingWidth - 4) {
        imgAct.width = 0;
    }
}

function LoadTable(content, imageURL, left, top) {
    var strLoading = "";
    strLoading += "<div id=\"showimage\" style=\"DISPLAY:none;Z-INDEX:100;LEFT:" + left
                + "px;POSITION:absolute;TOP:" + top + "px;\" align=\"center\">";
    strLoading += "<TABLE id=\"Table1\" cellSpacing=\"0\" cellPadding=\"0\" width=\""
                + loadingWidth + "\" border=\"0\" bgcolor=\"" + loadingBgcolor + "\">";
    if (content != "") {
        strLoading += "<tr><td align=\"center\">";
        strLoading += "<font size=\"4\" face=\"Courier New, Courier, mono\"><strong>"
                    + content + "</strong></font>";
        strLoading += "</td></tr><TR>";
    }
    strLoading += "<TD class=\"Loading\" height=\"8\">";
    strLoading += "<IMG id=\"imgAct\" height=\"8\" alt=\"\" src=\"" + imageURL + "\" width=\"0\">";
    strLoading += "</TD></TR></TABLE></div>";

    document.getElementById("loading_div").innerHTML = strLoading;
}

使用頁面:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<script src="LoadingJS/Loading.js" type="text/javascript"></script>
</head>
<body>
<input type="button" name="Button" value="Button"
    onclick="Loading('顯示標籤內容', 'LoadingJS/', 20, 100)">
<div id="loading_div"></div>
</body>
</html>

核心原理很單純:用一個寬度從0開始的img,每50毫秒加上3像素,超過上限就歸零重來。這種做法適合「不確定還要等多久」的情境,屬於一種活動 indicator,而非真實進度。

方法二:封裝成 Progress 類別

第二種做法把進度條封裝成可配置的類別,支援自訂寬高、位置、顏色、邊框,並提供完成回呼。

progress.js

$ = function (id) {
    return document.getElementById(id);
}

// 字串格式化方法
String.prototype.format = function () {
    var newStr = this;
    var reg = null;
    for (var i = 0; i < arguments.length; i++) {
        reg = RegExp('{' + (i) + '}', 'gm');
        newStr = newStr.replace(reg, arguments[i]);
    }
    return newStr;
};

// 進度條類
function Progress(objId) {
    this.interval = null;          // window.setInterval 物件
    this.id = objId;               // 進度條物件 ID
    this.progress = 0;             // 當前進度,起始為 0
    this.progressId = 'inner' + this.id;      // 顯示進度的 div ID
    this.progressFrameId = 'frame' + this.id; // 進度條邊框 ID
    this.config = {
        width: 150,
        height: 20,
        left: 0,
        top: 0,
        progressColor: 'red',
        borderColor: '#ccc',
        borderHeight: 2,
        hiddenSplit: 2000   // 進度完成後間隔N毫秒隱藏,0為立即隱藏
    };
}

// 初始化方法
Progress.prototype.init = function () {
    var progressdiv = document.createElement('div');
    var progressdiv_css_text = ('position:absolute;width:{0}px;height:{1}px;left:{2}px;top:{3}px;border:{4} {5}px solid;')
        .format(this.config.width, this.config.height, this.config.left,
                this.config.top, this.config.borderColor, this.config.borderHeight);
    this.progress = 0;
    progressdiv.id = this.progressFrameId;
    progressdiv.style.cssText = progressdiv_css_text;
    progressdiv.innerHTML = ('<div id="{0}" style="height:{1}px;background:{2};"></div>')
        .format(this.progressId, this.config.height, this.config.progressColor);
    document.body.appendChild(progressdiv);
};

// 隱藏函式
Progress.prototype.hiddenProgress = function () {
    document.body.removeChild(document.getElementById(this.progressFrameId));
    window.clearInterval(this.interval);
};

// 進度結束時觸發
Progress.prototype.complete = function () {
    window.clearInterval(this.interval);
    this.interval = window.setTimeout(this.id + ".hiddenProgress();", this.config.hiddenSplit);
    if (this.completeCallBack) {
        this.completeCallBack();
    }
};

// 每次運行後的回呼
Progress.prototype.callback = function () {
    var progressDiv = document.getElementById(this.progressId);
    var progressFrameDiv = document.getElementById(this.progressFrameId);
    progressDiv.innerHTML = (this.progress * 100) + ' %';
    progressFrameDiv.title = '上傳進度: ' + (this.progress * 100) + ' %';
    progressDiv.style.width = (this.progress * 100) + ' %';
    if (this.progress >= 1) {
        this.complete();
        progressDiv.innerHTML = '文件上傳成功!';
    }
};

// 進度條運行函式,需由使用者自行實作
Progress.prototype.run = function () {
    alert('請實現 ' + this.id + '.run方法以實現異步進度請求,回調' + this.id + '.callback方法。');
    window.clearInterval(this.interval);
};

// 啟動進度
Progress.prototype.start = function () {
    this.init();
    this.interval = window.setInterval(this.id + ".run();", 1000);
};

這個設計的關鍵在於把 run 留給使用者實作——真正要知道「上傳了多少」必須由呼叫端決定,類別只負責把 this.progress 這個0到1之間的比例視覺化。這樣的分層讓同一個元件可以套用在上傳、下載、批次處理等不同場景。

方法三:圖片載入進度即時顯示

若是圖集頁面,可以在載入完成後才顯示全部圖片,過程中先顯示百分比:

<script>
var l = 0;
var imgs = new Array();
var sum = 0;

function chk() {
    l--;
    document.getElementById("aa").innerText = "" + ((sum - l) * 100 / sum) + "%"
    if (l == 0) {
        for (var i = 0; i < sum; i++)
            document.body.innerHTML += "<img src='" + imgs[i].src + "'>"
    }
}

if (document.images) {
    imgs[0] = new Image()
    imgs[1] = new Image()
    imgs[2] = new Image()
    imgs[3] = new Image()
    imgs[4] = new Image()
    imgs[5] = new Image()
    imgs[6] = new Image()
    imgs[7] = new Image()
    imgs[0].src = "/articleimg/2006/08/3859/01.jpg";
    imgs[1].src = "/articleimg/2006/08/3859/02.jpg";
    imgs[2].src = "/articleimg/2006/08/3859/03.jpg";
    imgs[3].src = "/articleimg/2006/08/3859/04.jpg";
    imgs[4].src = "/articleimg/2006/08/3859/05.jpg";
    imgs[5].src = "/articleimg/2006/08/3859/06.jpg";
    imgs[6].src = "/articleimg/2006/08/3859/07.jpg";
    imgs[7].src = "/articleimg/2006/08/3859/08.jpg";
}
</script>
<body>
<div id="aa">0%</div>
<script>
sum = l = imgs.length;
for (var i = 0; i < l; i++) {
    imgs[i].onload = chk;
    imgs[i].onerror = chk;  // 無論載入成功或失敗,都執行同一個方法
}
</script>
</body>

這裡有個實務上很重要的細節:onerror 也綁定同一個處理函式。如果只監聽 onload,只要有一張圖片404,計數永遠湊不齊,進度就會卡在最後一格再也無法完成。把失敗也計入完成,是讓流程能收束的關鍵。

三種方式的適用場景

  • 方法一適合無法得知剩餘時間的等待提示,實作成本最低。
  • 方法二適合有明確百分比可回報的情境(如上傳、批次任務),可配置性最好。
  • 方法三專門解決資源預載,能改善圖集類頁面的閃現問題。

以今日的標準來看,若要重寫方法二,用 CSS transition 搭配 transform 來做寬度動畫會比 setInterval 逐格改寬度流暢得多,也能避免頻繁觸發重排(reflow)造成的效能損耗。

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