<!DOCTYPE html>
<html>
<head>
<style>
#divBar{ width:600px;height:100px; overflow:hidden;padding:0px; background-color:green;text-align:center;}
#divProgress{ width:0px;height:70px; overflow:hidden;padding:0px; background-color:red;}
</style>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
function load(){
var divBarWidth = $("#divBar").width();
var pw = $("#divProgress").width();
$("#divProgress").animate({width: divBarWidth}
,{duration:5000
,done:function(){// 这个方法会在99%的时候就执行了很奇怪,所以改在100%的时候再调用一样可以达到同样的效果
// alert("加载完成!");
},step:function(now,fx){
// $("#labText").text(calcPrecent());
// console.log("返回的CSS属性是:"+fx.prop);
// console.log("属性初始值:"+fx.start);
// console.log("属性结束值:"+fx.end);
// console.log("属性当前值:"+fx.now);
var divBarWidth = $("#divBar").width();
var val = parseInt(now / divBarWidth * 100 ) ;
$("#labText").text(val +"%");
if(val == 100){
alert("加载完成");
}
}});
}
// 这个是来回运动的动画效果
var forward = false; // 运动方向
function load2(){
forward = !forward;
var pw = $("#divProgress").width();
var w = $("#divBar").width();
$("#divProgress").stop();
if(forward){
$("#divProgress").animate({width: w},5000);
}else{
$("#divProgress").animate({width: 0},5000);
}
}
</script>
</head>
<body>
<div id="divBar">
<div id="divProgress"></div>
<label id="labText">0%</label>
</div>
<br />
<button onclick="load();" >加载动画</button>
<button onclick="load2();" >来回动画</button>
</body>
</html>