效果图:
源代码:
<!doctype html>
<html>
<head>
<meta charset='utf-8'/>
<title>碰壁反弹</title>
<style type="text/css">
#content{
height: 500px;
width: 500px;
border: 1px solid #000;
position: relative;
}
.boll {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: red;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div id="content">
</div>
<script type="text/javascript">
// 获取围栏
var content = document.querySelector('#content');
// 产生小球,并使其运动
function createAndRun(){
// 创建一个小球
var boll =document.createElement('div');
boll.className = 'boll';
content.appendChild(boll);
// 使用定时器让小球移动
var speendX = Math.floor(Math.random()*10);
var speendY = Math.floor(Math.random()*10);
setInterval(function () {
// 判断小球是否撞左右墙
if (boll.offsetLeft+boll.offsetWidth >= content.offsetWidth
|| boll.offsetLeft < 0) {
speendX*=-1;
}
// 判断小球是否撞上下墙
if (boll.offsetTop + boll.offsetHeight >= content.offsetHeight
|| boll.offsetTop <0 ) {
speendY*=-1;
}
//
boll.style.left = boll.offsetLeft + speendX +'px';
boll.style.top = boll.offsetTop + speendY +'px';
},10);
}
createAndRun();
// setInterval(createAndRun,1000);
</script>
</body>
</html>