原理就是用setTimeout 方法,很久之前写的代码了, 今天发现了,上传上来保存下。
效果是两个方块在一条直线上进行互相追击,速度快的碰撞到速度慢的就会减速,而被碰撞的就会加速。二者互相追击,碰撞。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <style> * { margin: 0; padding: 0; } #container { position: relative; margin: 120px auto; 800px; height: 40px; border: 1px solid red; box-sizing: border-box; color: #fff; } #box { position: absolute; 40px; height: 40px; background-color: #47acab; text-align: center; box-sizing: border-box; } #box2 { position: absolute; 40px; height: 40px; background-color: darkslateblue; text-align: center; box-sizing: border-box; } </style> <body> <div id="container"> <div id="box" style="left: 100px">box</div> <div id="box2" style="left: 180px">box2</div> </div> <script> (function () { var width = 800; var boxWidth = 40; var box = document.getElementById('box'); var box2 = document.getElementById('box2'); function play(step, time, div) { var obj = {}; obj.step = step; obj.time = time; obj.box = div; obj.pos = 0; /* 因为是靠left增加来移动方格,所以加方格的一个宽度,防止方移动到末尾后超出一个身位置*/ obj.go = function () { if (parseInt(obj.box.style.left) + boxWidth >= (width)) { obj.box.style.left = obj.pos + 'px'; } obj.box.style.left = parseInt(obj.box.style.left) + obj.step + 'px'; setTimeout(obj.go, obj.time) } return obj; } function create() { var a = play(1, 20, box); var b = play(1, 2, box2); a.go(); b.go(); check(); a_check() var b_count = 0; var a_count = 0; var fast = 2; function check() { if (Math.round(parseInt(b.box.style.left)) == Math.round(parseInt(a.box.style.left)) - boxWidth && a.time > b.time) { b.time = b.time * 2; a.time = a.time / 2; a.box.style.left = parseInt(a.box.style.left) + fast + 'px'; console.log("b碰撞次数: " + ++b_count); } setTimeout(check, b.time); } function a_check() { if (Math.round(parseInt(a.box.style.left)) == Math.round(parseInt(b.box.style.left)) - boxWidth && b.time > a.time) { a.time = a.time * 2; b.time = b.time / 2; b.box.style.left = parseInt(b.box.style.left) + parseInt(b.box.style.left) / 3 + 'px'; console.log("a碰撞次数: " + ++a_count + Math.round(parseInt(a.box.style.left))); } setTimeout(a_check, a.time); } } create(); })() </script> </body> </html>
您可以点击 这里查看demo