Native JS implements a div's collision bounce motion:
The key is to detect the boundary of the Div, and then change the direction of motion to achieve the impact rebound effect.
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>Title</title> <style> *{margin:0;}Div{Height:100px;width:100px;background:Red;position:Absolute;} /*Add absolute positioning*/ </style> <Script>window.onload=function(){ varbtn=document.getElementById ("btn"); varDiv=document.getElementById ("Div"); varSpeedx=6; varSpeedy=8; varT=NULL; Btn.onclick=function() {clearinterval (t); T=SetInterval (function(){ varL=Div.offsetleft+Speedx; varT=Div.offsettop+speedy; if(L>=Document.documentElement.clientWidth-div.offsetwidth) {Speedx*=-1; L=Document.documentElement.clientWidth-Div.offsetwidth; }Else if(L<=0) {Speedx*=-1; L=0; } if(t>=Document.documentElement.clientHeight-div.offsetheight) {Speedy*=-1; T=Document.documentElement.clientHeight-Div.offsetheight; }Else if(t<=0) {Speedy*=-1; T=0; }Div.style.left=L+"px"; Div.style.top=T+"px"; },Ten); } } </Script></Head><Body><inputtype= "button"ID= "BTN"value= "Start Motion"><DivID= "Div"></Div></Body></HTML>
Native JS realizes a Div's collision bounce motion