<!DOCTYPE html>
<html lang=”zh-TW”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>隨機氣泡效果</title>
<style>
body {
background-color: #1a1a2e;
margin: 0;
overflow: hidden;
height: 100vh;
}
.bubble {
position: absolute;
border-radius: 50%;
background: rgba(255, 255, 255, 0.2);
box-shadow: inset 0 0 10px rgba(255, 255, 255, 0.5);
animation: float linear infinite;
}
.bubble::after {
content: ”;
position: absolute;
top: 20%;
left: 20%;
width: 15%;
height: 15%;
border-radius: 50%;
background: rgba(255, 255, 255, 0.4);
}
@keyframes float {
50% {
transform: translateX(10px);
}
to {
transform: translateY(-100vh) translateX(10px);
}
}
</style>
</head>
<body>
<script>
document.addEventListener(‘DOMContentLoaded’, function() {
const body = document.body;
const bubbleCount = 20; // 氣泡數量
// 創建氣泡
for (let i = 0; i < bubbleCount; i++) {
createBubble();
}
// 每隔一段時間創建新氣泡
setInterval(createBubble, 1000);
function createBubble() {
const bubble = document.createElement(‘div’);
bubble.className = ‘bubble’;
// 隨機大小 (10px 到 100px)
const size = Math.random() * 90 + 10;
bubble.style.width = `${size}px`;
bubble.style.height = `${size}px`;
// 隨機位置 (水平)
bubble.style.left = `${Math.random() * 100}vw`;
bubble.style.bottom = `-${size}px`; // 從底部開始
// 隨機動畫持續時間 (5s 到 15s)
const duration = Math.random() * 10 + 5;
bubble.style.animationDuration = `${duration}s`;
// 隨機水平移動 (-10px 到 10px)
const horizontalMovement = Math.random() * 20 – 10;
bubble.style.setProperty(‘–horizontal-move’, `${horizontalMovement}px`);
// 隨機透明度 (0.1 到 0.4)
const opacity = Math.random() * 0.3 + 0.1;
bubble.style.background = `rgba(255, 255, 255, ${opacity})`;
// 氣泡上升完成後移除
bubble.addEventListener(‘animationend’, function() {
bubble.remove();
});
body.appendChild(bubble);
}
});
</script>
</body>
</html>
主要修改點:
- 速度與大小的關係:
- 我們先計算一個基礎持續時間(5-15秒)
- 然後根據氣泡大小調整這個持續時間:
- 小氣泡(10px):持續時間約為基礎的 55%
- 大氣泡(100px):持續時間約為基礎的 100%
- 這樣小氣泡會移動得更快,大氣泡移動得更慢
- 動畫調整:
- 使用
forwards
替代infinite
,因為我們會在動畫結束時手動移除氣泡 - 增加了
- 使用