js运动小球碰壁反弹
1、触碰窗口壁沿反弹,同时改变颜色
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>碰壁反弹</title>
<style>
#box {
margin: 50px auto 0;
width: 800px;
height: 600px;
border: 2px solid #ccc;
position: relative;
}
#subbox {
width: 50px;
height: 50px;
position: absolute;
border-radius: 50%;
top: 0;
left: 0;
background-color: lightblue;
}
</style>
</head>
<body>
<div id="box">
<div id="subbox"></div>
</div>
</body>
</html>
<script>
var box = document.getElementById('box');
var subbox = document.getElementById('subbox');
var leftMax = 800 - subbox.clientWidth;
var topMax = 600 - subbox.clientHeight;
// 定时器
var lTor = null;
// 每次变化的像素值
var lengLeft = 5;
var lengTop = 5;
console.log(topMax);
console.log(leftMax);
function leftToRight() {
var Left = subbox.offsetLeft + lengLeft;
var Top = subbox.offsetTop + lengTop;
if (Left >= leftMax) {
Left = leftMax;
lengLeft = -lengLeft;
changeColor(subbox);
} else if (Left <= 0) {
Left = 0;
lengLeft = -lengLeft;
changeColor(subbox);
};
if (Top >= topMax) {
Top = topMax;
lengTop = -lengTop;
changeColor(subbox);
} else if (Top <= 0) {
Top = 0;
lengTop = -lengTop;
changeColor(subbox);
}
subbox.style.top = Top + "px";
subbox.style.left = Left + "px";
}
function changeColor(obj) {
var a = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
var c = Math.floor(Math.random() * 255);
obj.style.background = "rgb(" + a + "," + b + "," + c + ")";
return obj;
}
box.onclick = function () {
// clearInterval(lTor);
lTor = setInterval(function () {
leftToRight();
}, 25)
}
</script>