给泡泡随机个数,随机颜色,随机位置,随机大小,再设置一下边界即可。
还有一个点击消失的功能。
出现的问题:
在设置边界的时候,可运动区域设置为窗口的文档显示区的高度和宽度减掉泡泡的自身的宽度和高度,这时泡泡触碰边界会出现抖动,是因为定时器没有关闭,但在需求中并不需要关闭定时器,泡泡需要一直运动,所以在设定边界之后还有一个防止抖动的功能,在泡泡触碰边界的时候直接让它的位置发生改变,离开边界,继续运动,类似于将泡泡从边界弹射过来,下面给它设置了一个8px的距离。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bubble</title>
<style>
* {
margin: 0;
padding: 0;
}
span {
width: 20px;
height: 20px;
display: inline-block;
border-radius: 50%;
position: absolute;
opacity: 0.5;
}
</style>
</head>
<body>
</body>
</html>
<script>
//将创建一个泡泡封装成一个函数
function Bubble(n) {
//创建传入的实参n个的泡泡
for (let i = 0; i < n; i++) {
let oBB = document.createElement("span");
document.body.appendChild(oBB);
}
let oBBs = document.querySelectorAll("span");
for (let i = 0; i < n; i++) {
let num = Math.round(Math.random() * 80 + 30); //泡泡的随机宽高
let num2 = Math.round(Math.random() * 700 + 80); //泡泡距离浏览器页面左上角的随机top
let num3 = Math.round(Math.random() * 1000 + 80); //泡泡距离浏览器页面左上角的随机left
let num4 = Math.round(Math.random() * 5 + 1); //泡泡的随机速度speedX
let num5 = Math.round(Math.random() * 5 + 1); //泡泡的随机速度speedY
//随机颜色
let color = "#";
let str = "0123456789abcdef";
for (let j = 0; j < 6; j++) {
let colnum = Math.round(Math.random() * 15);
color += str[colnum];
}
//获取以上随机数赋给对应的属性
oBBs[i].style.width = num + "px"; //泡泡的宽
oBBs[i].style.height = num + "px"; // 泡泡的高
oBBs[i].style.top = num2 + "px"; //泡泡的top值
oBBs[i].style.left = num3 + "px"; //泡泡的left值
oBBs[i].style.backgroundColor = color; //泡泡的颜色
rebound(oBBs[i], num4, num5); //调用rebound()函数,给泡泡的运动设置边界
oBBs[i].onclick = function () { //点击哪个泡泡,哪个泡泡就消失
this.style.display = "none";
}
}
}
Bubble(50); //调用创建泡泡的函数,并传入实参
function rebound(obj, x, y) {
let speedX = x; //速度x,即向右运动
let speedY = y; //速度y,即向左运动
setInterval(function () { //启用定时器,让泡泡一直运动
obj.style.left = obj.offsetLeft + speedX + "px"; //每50毫秒运动的left距离
obj.style.top = obj.offsetTop + speedY + "px"; //每50毫秒运动的top距离
//边界条件
if (obj.offsetLeft <= 0 || obj.offsetLeft >= innerWidth - obj.offsetWidth) {
//如果泡泡的左外边框到浏览器左内边框的距离小于0,即碰到左边界时
//或者泡泡的左外边框到浏览器左内边框的距离大于等于浏览器的宽-泡泡自身的宽度时,即碰到右边界时
speedX *= -1; //x反向,即碰到左右边界时,泡泡反弹的方向
//防止泡泡触边界抖动
if (obj.offsetLeft <= 0) { //碰到左边界时
obj.style.left = obj.offsetLeft + 8 + "px"; //泡泡的左外边框到浏览器左内边框的距离 + 8
} else if (obj.offsetLeft >= innerWidth - obj.offsetWidth) {
obj.style.left = obj.offsetLeft - 8 + "px";
}
}
if (obj.offsetTop <= 0 || obj.offsetTop >= innerHeight - obj.offsetHeight) {
speedY *= -1;
//防止泡泡触边界抖动
if (obj.offsetTop <= 0) {
obj.style.top = obj.offsetTop + 8 + "px";
} else if (obj.offsetTop >= innerHeight - obj.offsetHeight) {
obj.style.top = obj.offsetTop - 8 + "px";
}
}
}, 50);
}
</script>