<meta charset="utf-8">
<style type="text/CSS" & gt;
# box {
width: 100px;
Height: 100 px;
Background: # 000000;
position: absolute;
Left: 0 px;
}
# box1 {
width: 100px;
Height: 100 px;
Background: # FF0000;
position: absolute;
Left: 500 px;
Top: 500 px;
}
Body {
overflow: hidden;
}
* {
margin: 0;
padding: 0;
}
</style>
Var style=window. GetComputedStyle (el);
Var left=parseInt (style. Left);
Var top=parseInt (style. The top);
Var width=parseInt (style. The width);
Var height=parseInt (style. Height);
If (left & lt; 0 {
Left=0;
El. SpeedX *=1;
}
If (left & gt; Window. The innerWidth - width) {
Left=window. InnerWidth - width;
El. SpeedX *=1;
}
If (top & lt; 0 {
Top=0;
El. SpeedY *=1;
}
If (top & gt; Window. The innerHeight - height) {
Top=window. InnerHeight - height;
El. SpeedY *=1;
}
El. Style. Left=left + "px";
El. Style. The top=top + "px";
}
The function check_block_collision (block1, block2) {
Var left1=parseInt (window. GetComputedStyle (block1). Left);
Var top1=parseInt (window. GetComputedStyle (block1). Top);
Var width1=parseInt (window. GetComputedStyle (block1). Width);
Var height1=parseInt (window. GetComputedStyle (block1). Height);
//
Var left2=parseInt (window. GetComputedStyle (block2). Left);
Var ranked by=parseInt (window. GetComputedStyle (block2). Top);
Var width2=parseInt (window. GetComputedStyle (block2). Lwidth);
Var height2=parseInt (window. GetComputedStyle (block2). Height);
//
Var center1={
X: width1 left1 +/2,
Y: top1 + height1/2
};
Var center2={
X: width2 left2 +/2,
Y: ranked by + height2/2
};
Var diffx=Math. Abs (center1. X-ray center2. X);
Var diffy=Math. Abs (center1. Y - center2. Y);
If (diffx & lt; (width1 + width2)/2 & amp; & Diffy & lt; (height1 + height2)/2) {
return true;
}
return false;
}
Window. The onl oad=function () {
Var speedX=5;
Var speedY=3;
Var oDiv=document. GetElementById (" box ");
Var oDiv1=document. GetElementById (" box1 ");
ODiv. SpeedX=5;
ODiv. SpeedY=3;
ODiv1. SpeedX=5;
ODiv1. SpeedY=3;
The function move (el) {
Check_border_collision (el)
Var tmpX tmpY;
Check_block_collision (oDiv oDiv1);
If (check_block_collision (oDiv oDiv1)) {
TmpX=oDiv. SpeedX;
TmpY=oDiv. SpeedY;
ODiv. SpeedX=oDiv1. SpeedX;;
ODiv. SpeedY=oDiv1. SpeedY;
ODiv1. SpeedX=tmpX;
ODiv1. SpeedY=tmpY;
}
Var currentLeft=parseInt (window. GetComputedStyle (el) (" left "));
Var currentTop=parseInt (window. GetComputedStyle (el). The top).
Var left=currentLeft + el. SpeedX;
Var top=currentTop + el. SpeedY;
El. Style. The top=top + "px";
El. Style. Left=left + "px";
}
SetInterval (function () {
Move (oDiv)
Move (oDiv1)
}, 20);
}
</script>
<body>