计时器:id=setInterval(function (){},1000)开启计时器,每隔1s执行一次;clearInterval(id);结束计时器。
<div id="wrapper">10</div>
<button onclick="jian(this)">开始</button>
<script>
var _wrapper=document.getElementById("wrapper");
var num=_wrapper.innerText*1;
var id;
function jian(tag){
if(tag.innerText=="开始"){
//1、开始变结束
tag.innerText="结束";
//2、开启计时器
id=setInterval(function (){
num--;
_wrapper.innerHTML=num;
},1000);
console.log(id);
}else{
//1、结束变开始
tag.innerText="开始";
//2、停止计时器
clearInterval(id);
}
}
</script>
注:一定要注意function jian(tag)中的函数名尽量不要省略,可能会导致报错。
进度条:
css代码:
#wrapper{
width: 500px;
height: 50px;
border: 1.5px solid chocolate;
border-radius: 25px;
/* overflow: hidden; */
margin: 0 auto;
}
#first{
width: 10%;
height: 99%;
background-color: pink;
border-radius: 25px;
text-align: center;
line-height: 50px;
color: chocolate;
font-size: 20px;
border: 0;
}
<div id="wrapper">
<div id="first" style="width: 10%;">10%</div>
</div>
js:代码
<script>
var _first=document.getElementById("first")
var id=setInterval(function(){
var length=parseInt(_first.style.width);
_first.style.width=length+1+"%";
_first.innerHTML=_first.style.width;
// _first.innerHTML=length+1+"%";
if(_first.style.width=="100%"){
clearInterval(id);
_first.innerHTML="下载完成!"
}
},100);
</script>