js小球碰撞反弹

 
  
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
.box {
width: 500px;
height: 400px;
border: 1px solid black;
}
.ball {
width: 50px;
height: 50px;
background: blue;
border-radius: 50%;
}
</style>
</head>
<body>
<div class="box">
<div class="ball"></div>
</div>
<script type="text/javascript">
var box = document.querySelector('.box'); //盒子
var ball = document.querySelector('.ball'); //球
//速度变量
var speedX = 1;
var speedY = 3;
var time = 10; //以毫秒为单位
//偏移的总量
var x = 0;
var y = 0;
var timer = null;
function ballMove() {
x += speedX;
y += speedY;
var ky = box.offsetHeight - ball.offsetHeight;
var kx = box.offsetWidth - ball.offsetWidth;
if (y >= ky || y <= 0) {
speedY = -speedY;
}
if (x >= kx || x <= 0) {
speedX = -speedX
}
ball.style.transform = 'translate(' + x + 'px,' + y + 'px)'
}
//球自动移动 定时器
function autoMove() {
timer = setInterval('ballMove()', time);
}
function clear() {
clearInterval(timer);
}
ball.onmouseout = autoMove;
ball.onmouseover = clear;
autoMove();
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/HDFQQ188816190/article/details/78409358
今日推荐