js实现气泡
实现气泡效果的方法
在JavaScript中实现气泡效果可以通过CSS动画和动态元素创建结合完成。以下是具体实现方式:

基础HTML结构
<div id="bubble-container"></div>
CSS样式设置
.bubble {
position: absolute;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.6);
pointer-events: none;
animation: float 4s ease-in-out infinite;
}
@keyframes float {
0% {
transform: translateY(0) rotate(0deg);
opacity: 1;
}
100% {
transform: translateY(-100px) rotate(360deg);
opacity: 0;
}
}
JavaScript实现逻辑
function createBubble() {
const container = document.getElementById('bubble-container');
const bubble = document.createElement('div');
bubble.className = 'bubble';
const size = Math.random() * 30 + 10;
bubble.style.width = `${size}px`;
bubble.style.height = `${size}px`;
bubble.style.left = `${Math.random() * 100}%`;
bubble.style.bottom = '0';
bubble.style.animationDuration = `${Math.random() * 3 + 2}s`;
container.appendChild(bubble);
setTimeout(() => {
bubble.remove();
}, 4000);
}
// 定时创建气泡
setInterval(createBubble, 300);
鼠标交互气泡增强版
document.addEventListener('mousemove', (e) => {
const bubble = document.createElement('div');
bubble.className = 'bubble';
bubble.style.left = `${e.clientX}px`;
bubble.style.top = `${e.clientY}px`;
const size = Math.random() * 40 + 10;
bubble.style.width = `${size}px`;
bubble.style.height = `${size}px`;
document.body.appendChild(bubble);
setTimeout(() => {
bubble.remove();
}, 2000);
});
彩色气泡变体
function getRandomColor() {
const colors = ['#ff9999', '#99ff99', '#9999ff', '#ffff99', '#ff99ff'];
return colors[Math.floor(Math.random() * colors.length)];
}
function createColorBubble() {
const bubble = document.createElement('div');
bubble.className = 'bubble';
bubble.style.backgroundColor = getRandomColor();
// 其余创建逻辑与基础版相同
}
这些实现方式可以根据具体需求进行调整,如改变气泡大小、颜色、运动轨迹或出现频率等参数来达到不同的视觉效果。






