1

我正在尝试显示一个 HTML5 进度元素来显示大图像文件的下载进度。

我已经检查了这个论坛上已经发布的类似问题的一些答案,但他们似乎没有直接回答这个问题(或者更可能只是我的无知)或者他们变得非常技术性,因此远远超出了我的范围。

我已经下载了一个 HTML5 / JavaScript 示例文件,该文件显示了基本方法(参见下面的代码),但我不知道如何将此脚本链接到我的图像下载。

任何建议将不胜感激。

<!DOCTYPE html>
<html>
<head>
<title>Developer Drive | Displaying the Progress of Tasks with HTML5 | Demo</title>
<script type="text/javascript">

var currProgress = 0;

var done = false;

var total = 100;

function startProgress() {

var prBar = document.getElementById("prog");

var startButt = document.getElementById("startBtn");

var val = document.getElementById("numValue");

startButt.disabled=true;

prBar.value = currProgress;

val.innerHTML = Math.round((currProgress/total)*100)+"%";

currProgress++;

if(currProgress>100) done=true;

if(!done)
setTimeout("startProgress()", 100);

else    
{
document.getElementById("startBtn").disabled = false;
done = false;
currProgress = 0;
}
}
</script>
</head>
<body>

<p>Task progress:</p>
<progress id="prog" value="0" max="100"></progress> 
<input id="startBtn" type="button" value="start" onclick="startProgress()"/>
<div id="numValue">0%</div>

</body>
</html>
4

1 回答 1

3

如果您正在寻找跟踪XMLHttpRequest(可能是加载图像或其他任何内容)的进度,Adobe 有一个很好的例子Ctrl+U是你的朋友 :)

基本上,你会想要这样做:

var xhr = new XMLHttpRequest();
xhr.onprogress = function(e){

  // This tests whether the server gave you the total number of bytes that were
  // about to be sent; some servers don't (this is config-dependend), and
  // without that information you can't know how far along you are
  if (e.lengthComputable)
  {

    // e.loaded contains how much was loaded, while e.total contains
    // the total size of the file, so you'll want to get the quotient:
    progressBar.value = e.loaded / e.total * 100;

  }
  else
  {
    // You can't know the progress in term of percents, but you could still
    // do something with `e.loaded`
  }
};

Mozilla 的开发者网站有更多详细信息,如果您想看看可以做什么。

希望这对你来说已经足够了:)


PS:现在想来,我觉得没有理由不使用e.totalas progressBar.max,干脆推e.loadedprogressBar.value

于 2013-03-05T21:24:44.957 回答