<!DOCTYPE html><html><head> <title>float box</title> <style type="text/css"> *{ margin: 0; padding: 0; } div{ width: 100px; height: 100px; border: 3px solid #acc; position: absolute; overflow: hidden; } #box{top: 0px;} #box1{top: 150px;} #box2{top: 300px;} #box3{top: 450px;} </style></head><body><div id="box"><a href="http://hao.360.cn"><img src="page.jpg"/></a></div><div id="box1"><a href="http://hao.360.cn"><img src="page.jpg"/></a></div><div id="box2"><a href="http://hao.360.cn"><img src="page.jpg"/></a></div><div id="box3"><a href="http://hao.360.cn"><img src="page.jpg"/></a></div><script type="text/javascript"> //获取窗口宽高 var width=document.documentElement.clientWidth || document.body.clientWidth; var height=document.documentElement.clientHeight||document.body.clientHeight; var els=document.getElementsByTagName('div'); var totop=[],left=[],movetop=[],moveleft=[]; for(var i=0;i<els.length;i++){ totop[i]=els[i].offsetTop; left[i]=els[i].offsetLeft; movetop[i]=true; moveleft[i]=true; } function move(){ //任意两个盒子的碰撞检测 for(var i=0;i<els.length;i++){ for(var j=0;j<els.length;j++){ if(i!=j){ var oCheck=checkbox(els[i],els[j]); if(oCheck){ moveleft[i]=moveleft[i]?false:true; moveleft[j]=moveleft[j]?false:true; movetop[i]=movetop[i]?false:true; movetop[j]=movetop[j]?false:true; } } } } //检测盒子是否碰到窗口边缘 for(var i=0;i<els.length;i++) { if (left[i] <= 0) { moveleft[i] = true; } else if ((left[i] + 106) >= width) { moveleft[i] = false; } if (totop[i] <= 0) { movetop[i] = true; } else if ((totop[i] + 106) >= height) { movetop[i] = false; } } //移动盒子 for(var i=0;i<els.length;i++) { if (moveleft[i]) { left[i] += 1; } else { left[i] -= 1; } if (movetop[i]) { totop[i] +=1; } else { totop[i] -= 1; } els[i].style.left = left[i] + 'px'; els[i].style.top = totop[i] + 'px'; } if(true){ setTimeout(move,20); } } //碰撞检测 function checkbox(elsi,elsj) { var a=parseInt(elsi.offsetLeft),b=parseInt( elsj.offsetLeft),c=parseInt(elsi.offsetTop),d=parseInt(elsj.offsetTop); var leftcheck=Math.abs(a-b);var topcheck=Math.abs(c-d); if(leftcheck<=106&&topcheck<=106){ return 1; } else{ return 0; } } window.onload=move();</script></body></html>
添加回答
举报
0/150
提交
取消