首页 > 代码库 > Javascript:实操---碰壁反弹(无阻碍物)
Javascript:实操---碰壁反弹(无阻碍物)
CSS部分
<style type="text/css">
#wrap{
height: 300px;
width: 500px;
border: 1px solid #000;
position: relative;
}
#child{
position: absolute;
left: 0;
top: 0;
height: 50px;
width: 50px;
background-color: #ccc;
}
</style>
HTML部分
<div id="wrap">
<div id="child"></div>
</div>
JS部分
<script type="text/javascript">
window.onload=function(){
var oWrap=document.getElementById("wrap");
var oChild=document.getElementById("child");
var iMaxWidth=oWrap.clientWidht-oChild.offsetWidth;
var iMaxHeight=oWrap.clientHeight-oChild.offsetHeight;
var startX=2;
var startY=2;
var iLeft=oChild.offsetLeft;
var iTop=oChild.offsetTop;
setInterval(function(){
iLeft+=startX;
iTop+=startY;
if(iLeft>=iMaxWidth||iLeft<=0){
startX*=-1;
}
if(iTop>=iMaxHeight||iTop<=0){
startY*=-1;
}
oChild.style.left=iLeft+"px";
oChild.style.top=iTop+"px";
},30);
}
</script>