js实现气泡
实现气泡效果的方法
使用CSS和JavaScript可以轻松创建气泡效果。以下是一个简单的实现方法:
// 创建气泡元素
const bubble = document.createElement('div');
bubble.className = 'bubble';
document.body.appendChild(bubble);
// 随机位置和大小
const randomSize = Math.random() * 50 + 20;
const randomX = Math.random() * window.innerWidth;
const randomY = window.innerHeight + randomSize;
// 设置气泡样式
bubble.style.width = `${randomSize}px`;
bubble.style.height = `${randomSize}px`;
bubble.style.left = `${randomX}px`;
bubble.style.top = `${randomY}px`;
// 动画效果
function animateBubble() {
const currentY = parseFloat(bubble.style.top);
bubble.style.top = `${currentY - 1}px`;
if (currentY < -randomSize) {
bubble.remove();
} else {
requestAnimationFrame(animateBubble);
}
}
animateBubble();
CSS样式
需要添加以下CSS样式使气泡看起来更真实:
.bubble {
position: absolute;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.6);
box-shadow: 0 0 10px rgba(255, 255, 255, 0.8);
pointer-events: none;
transform: translateZ(0);
will-change: transform;
}
创建多个气泡
要创建多个气泡效果,可以使用以下代码:
function createBubbles(count) {
for (let i = 0; i < count; i++) {
setTimeout(() => {
const bubble = document.createElement('div');
bubble.className = 'bubble';
document.body.appendChild(bubble);
const size = Math.random() * 50 + 20;
const x = Math.random() * window.innerWidth;
const y = window.innerHeight + size;
bubble.style.width = `${size}px`;
bubble.style.height = `${size}px`;
bubble.style.left = `${x}px`;
bubble.style.top = `${y}px`;
animateBubble(bubble, size);
}, Math.random() * 2000);
}
}
function animateBubble(bubble, size) {
const speed = Math.random() * 2 + 1;
let y = parseFloat(bubble.style.top);
function frame() {
y -= speed;
bubble.style.top = `${y}px`;
// 轻微左右摆动
const x = parseFloat(bubble.style.left);
bubble.style.left = `${x + Math.sin(y * 0.01)}px`;
if (y < -size) {
bubble.remove();
} else {
requestAnimationFrame(frame);
}
}
requestAnimationFrame(frame);
}
createBubbles(20);
交互式气泡
添加鼠标交互效果,当鼠标移动时产生气泡:
document.addEventListener('mousemove', (e) => {
const bubble = document.createElement('div');
bubble.className = 'bubble';
document.body.appendChild(bubble);
const size = Math.random() * 30 + 10;
bubble.style.width = `${size}px`;
bubble.style.height = `${size}px`;
bubble.style.left = `${e.clientX - size/2}px`;
bubble.style.top = `${e.clientY - size/2}px`;
setTimeout(() => {
bubble.remove();
}, 1000);
});
性能优化
对于大量气泡,建议使用CSS动画而非JavaScript动画:
@keyframes float {
0% {
transform: translateY(0) translateX(0);
opacity: 1;
}
100% {
transform: translateY(-100vh) translateX(20px);
opacity: 0;
}
}
.bubble {
animation: float 5s linear forwards;
}
然后只需创建元素并设置随机属性即可,浏览器会处理动画。







