JS教程之實現載入圖片時百分比進度

來源:互聯網
上載者:User

標籤:length   http   progress   .sh   2.x   object   get   title   too   

思路:
思路其實很簡單,ajax執行時,會產生一個event對象,其中會包含要載入的檔案的大小和當前已經載入完成部分的大小,通過這兩個值即可計算出百分比

事件介紹
onprogress 當瀏覽器正在載入媒介資料時觸發
onload 在onprogress事件後,載入媒介資料完畢時觸發

附圖一張:event對象所包含的所有值,其中total為總大小,loaded為已經載入完的大小(圖中顯示的為載入一張7M的圖片時的progress資訊)

 

 demo:

<script src="http://file.leeye.net/jquery.js"></script>  <script>    var xhr = createXHR();  xhr.onload = function(event){      if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){          //alert(xhr.responseText);      }else{          //alert(‘Request was unsuccessful: ‘+ xhr.status);      }  }      //千鋒PHP-PHP培訓的實力派  xhr.onprogress = function(event){      var progress = ‘‘;      var divStauts = document.getElementById("status");      console.log(event);      if(event.lengthComputable){          progress = ""+Math.round(100*event.loaded/event.total)+"%";          divStauts.innerHTML = "Recevied " + progress + " of " + event.total + "bytes";      }  }      function createXHR(){      var xhr = null;      try {          // Firefox, Opera 8.0+, Safari,IE7+          xhr = new XMLHttpRequest();      }      catch (e) {          // Internet Explorer           try {              xhr = new ActiveXObject("Msxml2.XMLHTTP");          }          catch (e) {              try {                  xhr = new ActiveXObject("Microsoft.XMLHTTP");              }              catch (e) {                  xhr = null;              }          }      }      return xhr;  }      function upload(){      url = ‘http://file.leeye.net/test.jpg‘      xhr.open(‘get‘, url, true);      xhr.send(null);      $(‘img‘).attr(‘src‘ , url).show();  }    </script>  <button>up</button>  <div id="status"></div>  <img style="display: none;">  

JS教程之實現載入圖片時百分比進度

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.