1. 程式人生 > >JS教程之實現加載圖片時百分比進度

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

scrip 計算 show || microsoft resp fire open func

思路:
思路其實很簡單,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教程之實現加載圖片時百分比進度