首页 > 代码库 > Javascript:实操---碰壁反弹(有阻碍物)
Javascript:实操---碰壁反弹(有阻碍物)
CSS部分
<style>
*{
margin: 0px;
padding: 0px;
}
#main{
width: 700px;
height: 500px;
border: 1px solid black;
position: relative;
}
#child{
width: 30px;
height: 30px;
border-radius: 15px;
background-color: #ccc;
position: absolute;
left: 0;
top: 0;
}
#box{
width: 400px;
height:130px;
background-color: #ccc;
position: absolute;
top: 100px;
left: 150px;
}
</style>
HTML部分
<body>
<div id="main">
<div id="child"></div>
<div id="box"></div>
</div>
</body>
JS部分
<script type="text/javascript">
window.onload=function(){
var omain=document.getElementById("main");
var ochild=document.getElementById("child");
var obox=document.getElementById("box");
var startx=5;
var starty=5;
var maxh=omain.offsetHeight-ochild.offsetHeight;
var maxw=omain.offsetWidth-ochild.offsetWidth;
var ileft=ochild.offsetLeft;
var itop=ochild.offsetTop;
var boxl=obox.offsetLeft-ochild.offsetWidth;
var boxr=obox.offsetLeft+obox.offsetWidth;
var boxt=obox.offsetTop-ochild.offsetHeight;
var boxb=obox.offsetTop+obox.offsetHeight;
setInterval(function(){
ileft+=startx;
itop+=starty;
if(ileft<=0||ileft>=maxw){
startx*=-1;
}
if(itop<=0||itop>=maxh){
starty*=-1;
}
if(ileft==boxl&&itop<=boxb&&itop>=boxt){
startx*=-1;//box左边
}
if (ileft==boxr&&itop<=boxb&&itop>=boxt) {
startx*=-1;//box右边
};
if (itop==boxt&&ileft<=boxr&&ileft>=boxl) {
starty*=-1;//box上边
};
if (itop==boxb&&ileft<=boxr&&ileft>=boxl) {
starty*=-1;//box下边
};
ochild.style.left=ileft+"px";
ochild.style.top=itop+"px";
},10);
}
</script>