实现加载图片进度

<button id="upbtn">up</button>
<div id="status"></div>
<img style="display: none;" id="loadimg">


<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);
        }
    }


    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)+"%";

            progress = Math.round(100*event.loaded/1024);
//            divStauts.innerHTML = "Recevied " + progress + " of " + event.total + "bytes";
            divStauts.innerHTML = "Recevied " + progress + " kb ";
        }
    }


    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://dohko.img.chouti.com/CHOUTI_9B121D59AC024B09A1740EDF35B3D7CB_W500H281.gif'
        xhr.open('get', url, true);
        xhr.send(null);
        $('#loadimg').attr('src' , url).show();
    }

    $('#upbtn').click(function () {
        upload();
    })

</script>

猜你喜欢

转载自zhangweirong8990.iteye.com/blog/2392489