jQuery addClass example

Change class name on click in jQuery

by Jchermy

HTML

<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
    <div id='bar'>0%</div>
    <button class="runBtn">运行</button>
</body>
</html>

CSS

#bar{
  background: #409eff;
  border-radius:10px;
  height:20px;
  width:0px;
  line-height:20px;
  font-size:10px;
  color:#fff;
  margin:5px;
}
.runBtn{
  cursor:pointer;
  background-color:#409eff;
  border: 1px solid #dcdfe6;
  color:#fff;
  font-weight:500;
  width:50px;
  height:30px;
  border-radius: 5px;
  outline:none;
}

JavaScript

var timer;
$('.runBtn').click(function(){
    clearTimeout(timer);
    $('#bar').width(0);
    timer = setTimeout(function fn(){
      if($('#bar').width() < 500){
         $('#bar').width($('#bar').width()+5);
         $('#bar').text($('#bar').width()/5+'%');
         timer = setTimeout(fn,16);
      }else{
        clearTimeout(timer);
      } 
    },16);
 });