<!doctype html> <html> <head> <meta charset="UTF-8"> <title>碰撞检测</title> <script src="../js/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script> <style type="text/css"> * { margin: 0; padding: 0; } .wp { width: 600px; height: 500px; border: 1px solid; position: relative; } .box { width: 30px; height: 30px; background: red; position: absolute; border-radius: 50%; } .box2 { width: 100px; height: 100px; background: orange; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; } </style> </head> <body> <div class="wp"> <div class="box"></div> <div class="box2"></div> </div> </body> <script type="text/javascript"> var wp = $(".wp"); var box = $(".box"); var box2 = $(".box2") var bl = box.offset().left; var bt = box.offset().top; var bv = 1; var bv2 = 1; //随机数 function randomNum(min,max){ var choices = max - min + 1; var num = Math.floor(Math.random() * choices + min ); return num; } //随机颜色 function colorFun(num){ if(num==1){ wp.css('border',"1px solid rgb("+randomNum(0,255)+","+randomNum(0,255)+","+randomNum(0,255)+")"); }else{ box2.css('background',"rgb("+randomNum(0,255)+","+randomNum(0,255)+","+randomNum(0,255)+")"); } box.css('background',"rgb("+randomNum(0,255)+","+randomNum(0,255)+","+randomNum(0,255)+")"); } setInterval(function() { bl += bv; bt += bv2; if(bl == (wp.width() - box.width()) || bl <= 0) { bv *= -1; colorFun(1); } if(bt >= (wp.height() - box.height()) || bt <= 0) { bv2 *= -1; colorFun(1); } // 左侧 if(bl == (box2.offset().left - box.width()) && bt >= (box2.offset().top-box.height()) && bt <= (box2.offset().top + box2.height())) { bv *= -1; colorFun(); } // 上侧 if(bt == (box2.offset().top - box.height()) && bl >= (box2.offset().left- box.width()) && bl <= (box2.offset().left + box2.width())) { bv2 *= -1; colorFun(); } // 右侧 if(bl == (box2.offset().left + box2.width()) && bt >= (box2.offset().top-box.height()) && bt <= (box2.offset().top + box2.height())) { bv *= -1; colorFun(); } // 下侧 if(bt == (box2.offset().top + box2.height()) && bl >= (box2.offset().left- box.width()) && bl <= box2.offset().left + box2.width()) { bv2 *= -1; colorFun(); } box.css('left',bl + "px"); box.css("top" , bt + "px"); }, ) </script> </html>