zoukankan      html  css  js  c++  java
  • 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;">  
  • 相关阅读:
    Remove Duplicates from Sorted Array
    Longest Valid Parentheses
    Valid Parentheses
    Java [Leetcode 112]Path Sum
    Java [Leetcode 119]Pascal's Triangle II
    Java [Leetcode 102]Binary Tree Level Order Traversal
    Java [Leetcode 172]Factorial Trailing Zeroes
    奇异值分解(转载)
    Java [Leetcode 118]Pascal's Triangle
    Java [Leetcode 66]Plus One
  • 原文地址:https://www.cnblogs.com/gaohj/p/7017722.html
Copyright © 2011-2022 走看看