<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <style type="text/css"> #wai{ width: 100%; height: 30px; border: 1px solid red; background-color: gainsboro; } #nei{height: 30px; background-color: greenyellow; text-align: center; line-height: 30px; color: white;} </style> <body> <h1>JavaScript 百分比进度条</h1> <div id="wai"> <div id="nei" style="width: 10%;">10%</div> </div> <br /> <button onclick="dian()">点我</button> <!--加onclick事件--> </body> </html> <script> window.onload = function () { } function dian () { var nei = document.getElementById("nei"); //找到内部div元素 var width = 10 ; //起始宽度 var id = setInterval(frame,10); //定义id,用10毫秒调用frame的值 function frame () { if (width>=100) { clearInterval(id) //判断,如果宽度大于或等于100,清除 } else{ width++; nei.style.width = width + '%'; nei.innerHTML = width * 1 + "%" //在网页中写出nei的值 } } } </script>
输出结果