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


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

事件介紹
onprogress 當瀏覽器正在加載媒介數據時觸發
onload 在onprogress事件后,加載媒介數據完畢時觸發

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

 

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;">  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM