JavaScript实现载入页面进度条

下面这段代码用 JavaScript 模拟一个页面载入进度条:每隔 100 毫秒把进度增加 2%,同时向文本框中追加 ||,直到接近 100% 后跳转到指定页面。

<form name="loading">
  <p align="center">
    <font color="#ff0000" size="2" face="Arial">载入中,请稍等...</font><br>
    <input type="text" name="chart" size="46" style="font-weight: bolder; color: #ff0000;">
    <br>
    <input type="text" name="percent" size="47" style="color: #ff0000;">
  </p>
</form>

<script language="JavaScript">
<!--
var bar = 0;
var line = "||";
var amount = "||";

count();

function count() {
  bar = bar + 2;
  amount = amount + line;
  document.loading.chart.value = amount;
  document.loading.percent.value = bar + "%";

  if (bar < 99) {
    setTimeout("count()", 100);
  } else {
    window.location.href = "http://www.sina.com.cn/";
  }
}
//-->
</script>

需要注意的是,这只是一个“模拟进度条”,并不会真实检测页面资源的加载进度。它适合用于简单的等待提示,或者在执行固定时长的跳转前给用户一个视觉反馈。

如果要写得更符合现代浏览器习惯,可以避免使用 font 标签、document.loading、HTML 注释包裹脚本以及字符串形式的 setTimeout

<form id="loading">
  <p style="text-align: center;">
    <span style="color: #ff0000; font: 12px Arial;">载入中,请稍等...</span><br>
    <input id="chart" type="text" size="46" style="font-weight: bold; color: #ff0000;">
    <br>
    <input id="percent" type="text" size="47" style="color: #ff0000;">
  </p>
</form>

<script>
let bar = 0;
let amount = "||";
const line = "||";
const chart = document.getElementById("chart");
const percent = document.getElementById("percent");

function count() {
  bar += 2;
  amount += line;
  chart.value = amount;
  percent.value = `${bar}%`;

  if (bar < 99) {
    setTimeout(count, 100);
  } else {
    window.location.href = "http://www.sina.com.cn/";
  }
}

count();
</script>

如果只是做页面顶部的加载提示,也可以用 CSS 控制一个 div 的宽度,这样比在文本框里追加字符更自然。

资料来源:

http://blog.csdn.net/sangliu/article/details/8718685

Leave a Reply