setInterval( )定义和用法
setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。
setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的参数。
语法:
setInterval(code,millisec[,"lang"])
参数 | millisec |
code | 必需。要调用的函数或要执行的代码串。 |
millisec | 必须。周期性执行或调用 code 之间的时间间隔,以毫秒计 |
返回值:
一个可以传递给 Window.clearInterval() 从而取消对 code 的周期性执行的值。
实现代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>javaScript实现进度条——progressbar</title>
<!-- <link rel="stylesheet" type="text/css" href="new_file.css"> -->
<style>
.bar{
width:100%;
height:50px;
background-color: azure;
border:black solid 1px;
margin-bottom:20px;
padding:0px;
}
#animation{
width:0%;
height: 100%;
background-color: palevioletred;
opacity: 0.8;
margin: 0px;
}
.btn{
position: relative;
left:40%;
}
</style>
</head>
<body>
<div class="bar">
<div id="animation"></div>
</div>
<button onclick="changeBar()" id="btn">点我改变进度条</button>
<script>
var animation=document.getElementById("animation");
function changeBar(){
var pos=0;
// setInterval(函数,完成时间)
var id=setInterval(frame,5);
function frame(){
//宽度达到最大100% 就停止
if(pos==100){
clearInterval(id);
}else{
pos++;
//JavaScript可以改变css
animation.style.width=pos+"%";
}
}
}
</script>
</body>
</html>
结果展示