碰壁反弹的原理是很简单,稍稍学过一些前端的童鞋,应该都会知道元素具有定位的布局方式,在这里会用到元素的left和top值,当一个元素在一定的空间内,到了最右边,也就是left值最大就让其返回,同样top值也是一样。
好嘞,废话不多说,简单粗暴地直接上代码~
【注:有看不懂的地方或者写的不太完善的地方,都希望大家留言哦,萍子会好好改进,也会帮大家解答力所能及的问题!!!】
CSS代码部分:
<style>
#box{
width: 800px;
height: 500px;
position: relative;
border:1px solid red;
margin:50px auto 0;
}
#ball{
width: 50px;
height: 50px;
border-radius: 50%;
border:1px solid green;
position: absolute;
top: 0px;
left: 0px;
}
</style>
<body>
<div id="box">
<div id="ball"></div>
</div>
</body>
JS代码部分:
<script>
var box=document.getElementById('box');
var ball=document.getElementById('ball');
var x=0,y=0,timer1=null,movex=1,movey=1;
console.log(box.clientWidth-boll.clientWidth);//box的视宽800-小球的视宽50=750
console.log(box.clientWidth-boll.offsetWidth);//box的视宽800-小球自身带border的宽52=748
timer1=setInterval(function(){
if (movex) {//判断方向
x++;
if (x>=box.clientWidth-ball.clientWidth) {
movex=0;
}
}
else{
x--;
if (x<=0) {
movex=1;
}
}
ball.style.left=x+'px';
if (movey) {
y++;
if (y>=box.clientHeight-boll.clientHeight) {
movey=0;
}
}else{
y--;
if (y<=0) {
movey=1;
}
}
ball.style.top=y+'px';
},5)
</script>
效果图如下:
矩形的写法跟圆形没有区别,把ball的border-radius去掉就可以了。
另一种写法的碰撞检测:
CSS代码部分:
<style type="text/css">
*{
padding: 0;
margin: 0;
}
.box{
width: 900px;
height: 700px;
border: 1px solid black;
margin: 50px 50px;
position: relative;
}
.life{
width: 60px;
height: 60px;
background-color: pink;
position: absolute;
left: 0px;
top: 320px;
}
</style>
<div class="box">
<div class="life"></div>
</div>
JS代码部分:
<script type="text/javascript">
var box = document.getElementsByClassName("box")[0];
var life = document.getElementsByClassName("life")[0];
var dSpeed = 2;
var lSpeed = 1;
var timer = setInterval(function(){
if(life.offsetTop<0 || life.offsetTop+life.offsetHeight>box.offsetHeight){
dSpeed *= -1;
}
if(life.offsetLeft<0 || life.offsetLeft+life.offsetWidth>box.offsetWidth){
lSpeed *= -1;
}
life.style.top = life.offsetTop + dSpeed + "px";
life.style.left = life.offsetLeft + lSpeed + "px";
},5)
</script>
效果如下图:
以上所用到的:
***offsetTop/offsetLeft、
offsetWidth/offsetHeight、
clientWidth/clientHeight***
会在下一篇博文中为大家解释!!!