HTML
<input type="file" name="" id="file"> <div id="wrap"> <div id="bar"></div> <span>0%</span> </div>
CSS
#wrap{ height: 50px; border: 5px solid yellow; position: relative; text-align: center; line-height: 50px; font-size: 28px; font-weight: bold; } #bar{ height: 100%; 0; background: green; position: absolute; left: 0; z-index: -1; }
JS
var file = document.getElementById('file'); var wrap = document.getElementById('wrap'); var bar = document.getElementById('bar'); var wrapSpan = wrap.getElementsByTagName('span')[0]; var maxWidth = wrap.clientWidth; file.onchange = function(){ var f = this.files[0]; var xhr = new XMLHttpRequest(); xhr.open('post','php/post_file.php',true); xhr.onload = function(){ console.log(this.responseText); }; //上传过程中触发 xhr.upload.onprogress = function(ev){ /* ev.total上传文件的总大小 ev.loaded 当前上传的大小。 */ var scale = ev.loaded/ev.total; wrapSpan.innerHTML = (scale*100).toFixed(2)+'%'; bar.style.width = maxWidth*scale+'px'; // console.log(ev.total,ev.loaded); } var fd = new FormData(); fd.append('file',f); xhr.send(fd); };