本篇文章使用jquery和少量的js代码实现圆形loading动画。
主要使用window.requestAnimationFrame(callback)控制动画,步长参数控制动画的速度。
HTML部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Loading</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="css/loading.css">
<script type="text/javascript" src="js/jquery-min.js"></script>
</head>
<body>
<div id="wrapper">
<div id="box_container"> //背景元素,并包涵圆环和圆点
<div class="circle">
<div class="ball"></div>
</div>
<span id="process">Loading</span> //进度文字
</div>
</div>
</body>
<script type="text/javascript" src="js/loading.js"></script>
</html>
css部分:
*{
margin:0;
padding:0;
}
#wrapper{
width:100%;
height:100%;
}
#box_container{
position:absolute;
top:50%;
left:50%;
margin:-150px 0 0 -150px;
width:300px;
height:300px;
background: #2b8bd9;
}
#box_container .circle{
position:absolute;
top:50%;
left:50%;
margin:-100px 0 0 -100px;
width:200px;
height:200px;
border-radius: 120px;
border:4px solid #fff;
}
#box_container .ball{
position: absolute;
top: 28px;
left: 10px;
width: 20px;
height: 20px;
border-radius: 20px;
background: #ffffff;
}
#process{
position:absolute;
top:58%;
left:50%;
width:100px;
height:30px;
margin:-30px 0 0 -50px;
text-align: center;
color:#fff;
line-height: 19px;
font-size: 30px;
font-family: "黑体"
}
.rotateCircle{
animation:rotate 3s infinite;
-webkit-animation:rotate 3s infinite;
}
@keyframes rotate{
0% {transform :rotate(0deg);}
100% {transform: rotate(360deg);}
}
js部分:
$(function(){
var step=0;
var processvalue=0;
function loading(){
step+=4;
$(".circle").css("transform","rotate("+step+"deg)");
}
function processBar(){
if(processvalue<100){
processvalue+=0.3;
value=parseInt(processvalue);
$("#process").html(value+"%");
requestAnimationFrame(processBar);
requestAnimationFrame(loading);
}
else
{
cancelAnimationFrame(processBar);
cancelAnimationFrame(loading)
$("#process").html("Done!");
}
//console.log(value)
}
processBar();
})