继上一篇。。。
原生js实现一个DIV的碰撞反弹运动,并且添加重力效果
关键在于边界检测,以及乘以的系数问题,实现代码并不难,如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{margin:0;} div{height:100px;width:100px;background:red;position:absolute;} /*添加绝对定位*/ </style> <script> window.onload=function(){ var btn=document.getElementById("btn"); var div=document.getElementById("div"); var speedx=300; var speedy=200; var timer=null; btn.onclick=function(){ clearInterval(timer); timer=setInterval(function(){ speedy+=3; var l=div.offsetLeft+speedx; var t=div.offsetTop+speedy; if(t>=document.documentElement.clientHeight-div.offsetHeight){ speedy*=-0.8; speedx*=0.8; t=document.documentElement.clientHeight-div.offsetHeight; }else if(t<=0){ speedy*=-0.8; speedx*=0.8; t=0; } if(l>=document.documentElement.clientWidth-div.offsetWidth){ speedx*=-0.8; l=document.documentElement.clientWidth-div.offsetWidth; }else if(l<=0){ speedx*=-0.8; l=0; } if(Math.abs(speedx)<1){ speedx=0; } if(Math.abs(speedy)<3){ //注意这块儿 speedy=0; } if(speedx==0&&speedy==0){ console.log(speedx+" "+speedy); clearInterval(timer); } div.style.left=l+"px"; div.style.top=t+"px"; },10); } } </script> </head> <body> <input type="button" id="btn" value="开始运动"> <div id="div"></div> </body> </html>