js定時器應用一則

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jquery實現進度條</title>
<style>
 .progressBar{width:300px;height:30px;border:1px solid #98AFB7;border-radius:5px;margin-top:10px;}
 #bar{width:0px;height:30px;background:#5EC4EA;}
</style>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
<script type="text/javascript">
  var arr = new Array();
  arr.push('1 春種一粒粟,秋收萬顆子。');
  // 這個超出顯示區域長度,會斷句,新增到下一行
  arr.push('2 四海無閒田,農夫猶餓死。1 春種一粒粟,秋收萬顆子。');
  arr.push('3 鋤禾日當午,汗滴禾下土。');
  arr.push('4 誰知盤中餐,粒粒皆辛苦。');

  var bar;
  var lineNum = 0;
  var lineWidth = 0;
  var status = 0;
  var contentMaxLength = 20;

 function progressBar(){
    // 開始&&繼續
    if(status == 0){
        $('#btn').val('暫停');
        status = 1;
        setTimer();
    }else{
        $('#btn').val('繼續');
        status = 0;
        clearInterval(bar);
    }
 }

 function setTimer(){
    var speed = 20;
        bar = setInterval(function(){
          nowWidth = parseInt($("#bar").width());
          //寬度要不能大於進度條的總寬度
          if(nowWidth <= lineWidth && lineWidth != 0){
            var barWidth = (nowWidth + 1)+"px";
            $("#bar").css("width", barWidth);
          }else{
            content();
          } 
      }, speed);
 }

 function content(){
    if(lineNum >= arr.length){
      $('#btn').val('重新開始');
      status = 0;
      lineNum = 0;
      clearInterval(bar);
    }else{
      $("#bar").css("width","0px");
      var content = arr[lineNum];
      if(content.length <= contentMaxLength){
          $("#text").html(content);
      }else{
          // 超出部分需要加入到數組中
          var view = content.substring(0, contentMaxLength);
          var newLine = content.substring(contentMaxLength);
          arr.splice(lineNum + 1, 0, newLine);
          $("#text").html(view);
          console.log('?');
      }
      lineWidth = parseInt($("#text").css("width"));
      lineNum++;
    }
 }
</script>
</head>
<body>
 <input id="btn" type="button" value="開始" οnclick="progressBar()" />
 <div class="progressBar">
    <div id="bar" style="position:absolute; "></div>
    <div id="text" style="position:absolute; "></div>
  </div>
</body>
</html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章