写了个超级简单的“进度条”的demo,供新手参考,高手吐槽!

<!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>
    <title>javascript进度条DEMO 作者:记忆中的马肠河</title>
 
 <script type="text/javascript"> 
 function ProgressBar(BarID){
    this.BarObj=document.getElementById(BarID); 
    this.BarObj.style.width='100px';
    this.BarObj.style.height='10px';
    this.BarObj.style.border='1px solid black';
    
 } 
ProgressBar.prototype.progressRateTo=function(pr){
    //如果不传参数默认为100,timerID为定时器ID,divControlRate为控制进度条宽度的div,showRateDiv用于展示进度%的div
    var pRate=parseInt(pr)||100,timerID,divControlRate,showRateDiv=document.createElement("div"); showRateDiv.style.position='absolute';showRateDiv.id='showRate';
    //如果pr大于100 赋值为100
    pRate =    pr>100?100:pr;  
    if(this.BarObj.getElementsByTagName("div").length==0){
    var d=document.createElement("div");
    d.style.width="0px";d.style.height="10px";
    d.style.backgroundColor='red';
    this.BarObj.appendChild(d);  
    divControlRate=d;
    }else{ 
    divControlRate=this.BarObj.getElementsByTagName("div")[0];
    divControlRate.style.width=divControlRate.clientWidth+1+"px";
    }
    if(document.getElementById("showRate")){
    this.BarObj.removeChild(document.getElementById("showRate"));
    } 
    //进度百分比计算
    var f=Math.floor(divControlRate.clientWidth/this.BarObj.clientWidth*100)+"%";
    showRateDiv.style.top=divControlRate.offsetTop+divControlRate.offsetHeight+"px";
    showRateDiv.style.left=divControlRate.offsetLeft+divControlRate.offsetWidth+"px";
    //放到div里
    showRateDiv.innerHTML=f; 
    //把控制进度条的进度的div加进进度条
    this.BarObj.appendChild(showRateDiv); 
    if(divControlRate.clientWidth==pRate){
    clearTimeout(timerID);
    return;
    }
    //把this赋值给self,以便setTimeout调用函数
    var self=this;
    timerID = setTimeout(function(){
    self.progressRateTo(pRate);
    },20);
}
window.onload=function(){
    var pb=new ProgressBar("div1");
    pb.progressRateTo(120); 
} 
</script>   
</head>
<body>
  <div id='div1'></div>
</body>
</html>

 

posted on 2013-03-28 10:11  Mr Code  阅读(521)  评论(0编辑  收藏  举报

导航