进度条,并显示进度百分比

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        *{margin:0;padding:0;}
        #parent{
            width: 300px;
            height: 40px;
            border: 1px solid #ccc;
            border-radius: 20px;
            margin: 30px auto;
        }

        #child{
            width: 0;
            height: 40px;
            border-radius: 20px;
            background: red;
        }
        #bfb{width: 50px;
            margin: 0 auto;
            font-size: 30px;    
        }

    </style>
</head>
<body>
    <div id="parent">
        <div id="child">
            
        </div>
    </div>
    <div id="bfb">
    
    </div>
    
</body>
</html>
<script>
var parent = document.getElementById("parent");
var child = document.getElementById("child");
var timer = null;
//加上百分比
timer = setInterval(function(){
   var speed = parseInt(Math.random()*4);

   if(child.offsetWidth>parent.offsetWidth){
           clearInterval(timer)
   }else{
        child.style.width = child.offsetWidth+speed+"px";
   }  
   
   var n = (child.offsetWidth/parent.offsetWidth)>1?1:(child.offsetWidth/parent.offsetWidth);   //n为加载的宽度占总宽度的比
   
   document.getElementById("bfb").innerText=parseInt(n*100)+"%";
},30)
        




</script>

猜你喜欢

转载自www.cnblogs.com/ngdty/p/9483500.html