DIV CSS 佈局教程網

用 JavaScript 手寫進度條:開始、暫停、清除
編輯:JavaScript綜合知識     

以下分享兩個進度條實作:一個是純 JavaScript 版本,具備開始、暫停與清除功能;另一個示範如何與 ASP.NET 後端搭配,在伺服器處理過程中即時更新進度。

範例一:純前端的進度條

用 setTimeout 每 500 毫秒推進 10%,並以三顆按鈕控制流程:

<!doctype html>
<html>
<head>
<meta charset="utf8">
<title>Process Bar</title>
<script>
var t;

function s(c) {
  if (c <= 100) {
    val.style.width = c + "%";
    percent.innerHTML = c + "%";
    btn.disabled = true;
    btnp.disabled = false;
    c = c + 10;
    t = setTimeout("s(" + c + ")", 500);
  } else {
    clearTimeout(t);
    btnc.disabled = false;
    btnp.disabled = true;
    return;
  }
}

function c() {
  clearTimeout(t);
  val.style.width = "0px";
  percent.innerHTML = "0%";
  btn.disabled = false;
  btnc.disabled = true;
  btnp.disabled = true;
  btnp.value = 'Pause';
}

function p() {
  var temp;
  if ('Pause' == btnp.value) {
    clearTimeout(t);
    btnp.value = 'Go on';
    btnc.disabled = false;
  } else {
    temp = val.style.width;
    btnp.value = 'Pause';
    var k = parseInt(delEnd(temp));
    s(k);
    btnc.disabled = true;
  }
}

function delEnd(str) {
  var temp = "";
  for (var i = 0; i < str.length - 1; i++) {
    temp = temp + str[i];
  }
  return temp;
}
</script>
</head>

<body>
<div id="bar" style="width:300px; height:30px; border:solid 1px; float:left;">
  <div id="val" style="height:100%; background-color:#03F; width:0px;"></div>
</div>
<div id="percent" style="float:left; line-height:30px;">0%</div>
<div style="clear:both"></div>
<br />
<input id="btn" type="button" value="Start" onClick="s(0)" />
<br />
<input id="btnc" type="button" value="Clear" onClick="c()" disabled />
<br />
<input id="btnp" type="button" value="Pause" onClick="p()" disabled />
</body>
</html>

暫停的實作思路是記住目前寬度,繼續時再從該處接著跑。範例中用 delEnd 去掉百分比尾巴,實務上直接用 parseInt(val.style.width) 就好,省去這個函式。

範例二:搭配 ASP.NET 的伺服器端進度回報

建立 Web 專案後新增一個 HTML 頁面 ProgressBar.htm:

<html xmlns="https://www.w3.org/1999/xhtml" id="mainWindow">
<head>
<title>處理中</title>
<script language="javascript">
function SetPorgressBar(pos) {
  // 讓進度條置中
  var screenHeight = window["mainWindow"].offsetHeight;
  var screenWidth = window["mainWindow"].offsetWidth;
  ProgressBarSide.style.width = Math.round(screenWidth / 2);
  ProgressBarSide.style.left = Math.round(screenWidth / 4);
  ProgressBarSide.style.top = Math.round(screenHeight / 2);
  ProgressBarSide.style.height = "21px";
  ProgressBarSide.style.display = "";

  // 更新百分比
  ProgressBar.style.width = pos + "%";
  ProgressText.innerHTML = pos + "%";
}

function SetCompleted() {
  ProgressBarSide.style.display = "none";
}
</script>
</head>
<body>
<div id="ProgressBarSide"
     style="position:absolute;height:21px;width:100px;color:Silver;
            border-width:1px;border-style:Solid;display:none">
  <div id="ProgressBar" style="position:absolute;height:21px;width:0%;background-color:#3366FF"></div>
  <div id="ProgressText" style="position:absolute;height:21px;width:100%;text-align:center"></div>
</div>
</body>
</html>

後端 Default.aspx.cs 負責把這個頁面寫出、再逐段推送更新指令:

using System.IO;

public partial class _Default : System.Web.UI.Page {

  private void beginProgress() {
    // 先把進度條介面輸出到用戶端
    string templateFileName = Path.Combine(Server.MapPath("."), "ProgressBar.htm");
    StreamReader reader = new StreamReader(
      templateFileName, System.Text.Encoding.GetEncoding("GB2312"));
    string html = reader.ReadToEnd();
    reader.Close();
    Response.Write(html);
    Response.Flush();
  }

  private void setProgress(int percent) {
    string jsBlock = "<script>SetPorgressBar('" + percent.ToString() + "');</script>";
    Response.Write(jsBlock);
    Response.Flush();
  }

  private void finishProgress() {
    string jsBlock = "<script>SetCompleted();</script>";
    Response.Write(jsBlock);
    Response.Flush();
  }

  private void Page_Load(object sender, System.EventArgs e) {
    beginProgress();

    for (int i = 1; i <= 100; i++) {
      setProgress(i);
      // 這裡以 Thread.Sleep 模擬耗時作業,實務上換成資料處理即可
      System.Threading.Thread.Sleep(50);
    }

    finishProgress();
  }
}

關鍵是每一段輸出後都要呼叫 Response.Flush(),否則瀏覽器只會等到整份回應結束才一次呈現,進度條就完全不動了。另外,這種長時間佔用請求的作法在真實環境中需留意 IIS 的執行逾時設定;若處理時間很長,改用 WebSocket 或串流回應會更合適。

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