如何使用 JavaScript 实现一个简单的加载进度条功能? - 项越资源网-html css js 用法分享社区-开发交流-项越资源网

如何使用 JavaScript 实现一个简单的加载进度条功能?

要实现一个加载进度条功能,首先您需要了解 JavaScript 中的 XMLHttpRequest 和 onprogress 事件。

这个函数可以用来从 Web 服务器初始化和执行请求,onprogress 可以用来更新给定的 SPA (Single Page Application) 的进度条:

// Initialize the XMLHttpRequest Object.
var xhr = new XMLHttpRequest();
xhr.open("GET", "/my-data", true);

// Create a function that gets called when the state of the request changes.
xhr.onprogress = function(event){
  // Calculate the progress percentage.
  var percentComplete = (event.loaded / event.total) * 100;
  
  // Update the progress bar with the new percentage.
  document.getElementById("progressBar").value = percentComplete;
}

// When the request is completed, change the state of the progress bar.
xhr.onloadend = function(){
  if(xhr.status == 200){
    // If the request was successful, change color of the progress bar to green.
    document.getElementById("progressBar").style.backgroundColor = "green"
  }else{
    // Otherwise, show an error.
    console.log("There was an error loading the data.");
  }
}

// Send the request.
xhr.send();
请登录后发表评论

    没有回复内容