圖片會在視窗可視區域內隨機跳躍移動,碰到邊界自動反彈,像個頑皮的精靈在螢幕上亂竄。
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>隨機飄浮圖片</title>
<style>
#floater {
position: fixed; /* 固定於視窗,不隨捲動 */
z-index: 9999; /* 置於最上層 */
pointer-events: none; /* 不阻擋點擊下層元素 */
user-select: none; /* 禁止選取 */
}
#floater img {
display: block;
width: 120px; /* 可依圖片調整 */
height: auto;
}
</style>
</head>
<body>
<div id="floater">
<img src="https://via.placeholder.com/120x120/ff6b6b/fff?text=👻" alt="浮動吉祥物">
</div>
<script>
const floater = document.getElementById('floater');
const img = floater.querySelector('img');
// 等待圖片載入以取得實際尺寸
img.onload = initFloater;
if (img.complete) initFloater(); // 快取情況
function initFloater() {
const imgW = img.offsetWidth;
const imgH = img.offsetHeight;
// 可移動範圍 = 視窗尺寸 - 圖片尺寸
const maxX = window.innerWidth - imgW;
const maxY = window.innerHeight - imgH;
let x = Math.random() * maxX;
let y = Math.random() * maxY;
let vx = (Math.random() - 0.5) * 6; // -3 ~ 3 px/frame
let vy = (Math.random() - 0.5) * 6;
floater.style.left = x + 'px';
floater.style.top = y + 'px';
function animate() {
// 邊界檢測與反彈
if (x <= 0 || x >= maxX) vx = -vx;
if (y <= 0 || y >= maxY) vy = -vy;
x += vx;
y += vy;
floater.style.left = x + 'px';
floater.style.top = y + 'px';
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
}
</script>
</body>
</html>
position: fixed + z-index: 讓圖片脫離文件流,固定在視窗座標系,永遠置於最上層。pointer-events: none: 關鍵屬性,讓滑鼠事件穿透圖片,不影響下方連結或按鈕點擊。requestAnimationFrame 動畫迴圈: 比 setInterval 更平滑、省電,自動隨螢幕重繪率同步。vx/vy 取反,模擬彈性碰撞。floater 實例,各自獨立速度與方向。vy += gravity、vx *= friction 模擬物理感。單一小圖片(<100KB)對效能影響極微。若部署多個大圖或複雜動畫,請考慮:
transform: translate() 取代 left/top 觸發 GPU 加速。postMessage 同步座標)。prefers-reduced-motion 媒體查詢。幾十行代碼即可為網站增添生動趣味元素,適合作為 404 頁面、節日活動頁或個人部落格的點睛之筆。