js实现进度条

时间:2023-03-09 17:08:53
js实现进度条

不多说,直接上代码

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ProgressBar</title>
<style>
*{
margin: 0;
padding: 0;
}
#progress{
width: 100%;
height: 30px;
background: rgb(42, 138, 248);
}
#bar{
width: 1%;
height: 28px;
margin-top: 1px;
background: purple;
} </style> </head>
<body>
<div id="progress">
<div id="bar"></div>
</div>
<div><h3 id="text-progress">0%</h3></div>
<input type="button" id=“btn” value="点击开始" onclick="action()">
</body>
<script>
function action(){
var iSpeed=1;
obj=setInterval(function(){
iSpeed+=1;
if(iSpeed>=100){ // 设置达到多少进度后停止
clearInterval(obj);
}
bar.style.width=iSpeed+'%';
document.getElementById('text-progress').innerHTML=iSpeed+'%'; },100); // 1s后函数执行一次
}
</script>
</html>

  结果

js实现进度条

写完之后发现有个bug,点击开始后再次点击进度条会再次执行

解决办法:1、点击开始后,将button的disabled设置为disabled,使不能再次点击

     2、添加判断,给出message提示,如果进度条在进行中再次点击给一个alter提示