js模拟抛物运动和惯性运动
一.普通移动
利用请求动画帧requesrannamitionframe()----16.67ms执行一次
1.布局
<body>
<div class="wrap">
<div class="ball"></div>
</div>
</body>
2.CSS样式
<style>
.wrap{
width: 1200px;
height: 600px;
background-color: aqua;
margin: 50px auto;
position: relative;
}
.ball{
width: 100px;
height: 100px;
background-color: red;
/* 设置圆角*/
border-radius: 50%;
position: absolute;
left: 0;
top: 0;
}
</style>
3.js实现(递归函数实现)
<script>
var spX = 3;
var spY = 3;
var oB = document.querySelector(".ball");
var oW = document.querySelector(".wrap");
requestAnimationFrame(function moveBall (){
oB.style.left = oB.offsetLeft+spX+"px";
oB.style.top =oB.offsetTop+spY+"px";
requestAnimationFrame(moveball);//递归函数持续进行
}
二.在固定范围内运动
*大于最大值就把当前最大值给他并且速度取反
requestAnimationFrame(function moveBall (){
var wL = oB.offsetLeft + spX;
var wT = oB.offsetTop + spY;
//右
if(wL>=oW.offsetWidth-oB.offsetWidth){
wL = oW.offsetWidth-oB.offsetWidth;
spX = -spX;
}
//左
if(wL<=0){
wL = 0;
spX = -spX;
}
//下
if(wT>=oW.offsetHeight-oB.offsetHeight){
wT = oW.offsetHeight-oB.offsetHeight;
spY = -spY;
}
//上
if(wT<=0){
wT &#