<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
html,
body {
height: 100%;
}
body {
margin: 0;
padding: 0;
overflow: hidden;
}
.box {
width: 300px;
height: 300px;
background-color: pink;
position: absolute;
border-radius: 50%;
z-index: -1;
}
#start {
padding: 3px 10px;
margin-left: 10px;
margin-top: 10px;
}
</style>
</head>
<body>
<button id="start" type="button">开始</button>
<button id="stop" type="button">停止</button>
<button id="changeBg" type="button">更换背景色</button>
<div class="box" style="left: 0;top: 0;"></div>
<script type="text/javascript">
var inter; //定义一个变量,循环计时器
var start = document.querySelector("#start");
var stop = document.querySelector("#stop");
// console.log(document.body.offsetHeight);
// console.log();
start.addEventListener("click", function() {
var box = document.querySelector(".box");
//生成随机方向,1左 2右 3上 4 下
//5左上,6右上 7左下, 8右下
var direction = parseInt(Math.random() * 8) + 1;
// console.log(direction);
//循环的定时器
// clearInterval(inter);
inter = setInterval(function() {
//字符串
var boxLeft = box.style.left;
var boxTop = box.style.top;
//字符串替换函数
boxLeft = boxLeft.replace("px", "");
boxLeft = parseFloat(boxLeft);
boxTop = boxTop.replace("px", "");
boxTop = parseFloat(boxTop);
//目标位置,数字
var target = {
left: boxLeft,
top: boxTop
};
//重新定义位置
if (direction == 1) {
target.left -= 5;
} else if (direction == 2) {
target.left += 5;
} else if (direction == 3) {
target.top -= 5;
} else if (direction == 4) {
target.top += 5;
} else if (direction == 5) { //左上
target.top -= 5;
target.left -= 5;
} else if (direction == 6) { //右上
target.top -= 5;
target.left += 5;
} else if (direction == 7) { //左下
target.top += 5;
target.left -= 5;
} else if (direction == 8) { //右下
target.top += 5;
target.left -= 5;
}
//判断目标位置是否溢出
if (target.top <= 0 || target.top >= document.body.offsetHeight - 200 || target.left < 0 || target.left >
document.body.offsetWidth - 300) {
direction = parseInt(Math.random() * 8) + 1;
} else {
box.style.left = target.left + "px";
box.style.top = target.top + "px";
}
}, 5);
});
stop.addEventListener("click", function() {
//定时器清除
clearInterval(inter);
});
//更换背景色
var change = document.querySelector("#changeBg");
change.addEventListener("click", function() {
setInterval(function() {
var r = parseInt(Math.random() * 256);
var g = parseInt(Math.random() * 256);
var b = parseInt(Math.random() * 256);
document.querySelector(".box").style.backgroundColor = "rgb(" + r + "," + g + "," + b + ")";
}, 100);
});
</script>
</body>
</html>
小球移动变色
最新推荐文章于 2021-01-24 17:38:22 发布