css制作冒泡
使用CSS制作冒泡效果
通过CSS的animation和@keyframes可以实现动态冒泡效果。以下是一个完整的实现方法:
HTML结构
<div class="bubble-container">
<div class="bubble"></div>
</div>
CSS样式
.bubble-container {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
background-color: #87CEEB;
}
.bubble {
position: absolute;
width: 30px;
height: 30px;
background-color: rgba(255, 255, 255, 0.7);
border-radius: 50%;
bottom: 0;
left: 50%;
transform: translateX(-50%);
animation: bubble-rise 4s infinite ease-in;
}
@keyframes bubble-rise {
0% {
transform: translateY(0) translateX(-50%);
opacity: 0;
}
10% {
opacity: 1;
}
100% {
transform: translateY(-300px) translateX(-50%);
opacity: 0;
}
}
创建多个随机冒泡
要创建多个随机出现的冒泡,可以添加更多气泡元素并使用CSS变量控制动画延迟:
HTML
<div class="bubble-container">
<div class="bubble" style="--delay: 0s; --duration: 4s; --size: 20px;"></div>
<div class="bubble" style="--delay: 1s; --duration: 5s; --size: 30px;"></div>
<div class="bubble" style="--delay: 2s; --duration: 6s; --size: 15px;"></div>
</div>
更新CSS
.bubble {
position: absolute;
width: var(--size, 20px);
height: var(--size, 20px);
background-color: rgba(255, 255, 255, 0.7);
border-radius: 50%;
bottom: 0;
left: calc(10% + (80% * random()));
animation: bubble-rise var(--duration, 4s) infinite ease-in var(--delay, 0s);
}
@keyframes bubble-rise {
0% {
transform: translateY(0);
opacity: 0;
}
10% {
opacity: 1;
}
100% {
transform: translateY(-300px);
opacity: 0;
}
}
添加更逼真的效果
为了使冒泡更逼真,可以添加轻微的水平移动和大小变化:
@keyframes bubble-rise {
0% {
transform: translateY(0) translateX(0);
opacity: 0;
width: var(--size, 20px);
height: var(--size, 20px);
}
10% {
opacity: 1;
}
50% {
transform: translateX(10px);
width: calc(var(--size, 20px) * 1.1);
height: calc(var(--size, 20px) * 1.1);
}
100% {
transform: translateY(-300px) translateX(-10px);
opacity: 0;
width: var(--size, 20px);
height: var(--size, 20px);
}
}
使用JavaScript动态生成气泡
对于更动态的效果,可以使用JavaScript动态创建气泡:

const container = document.querySelector('.bubble-container');
function createBubble() {
const bubble = document.createElement('div');
bubble.className = 'bubble';
const size = Math.random() * 30 + 10;
const duration = Math.random() * 3 + 3;
const delay = Math.random() * 2;
const left = Math.random() * 100;
bubble.style.cssText = `
--size: ${size}px;
--duration: ${duration}s;
--delay: ${delay}s;
left: ${left}%;
`;
container.appendChild(bubble);
setTimeout(() => {
bubble.remove();
}, duration * 1000);
}
setInterval(createBubble, 300);






