經典「飛動廣告」:圖片在視口內隨機反彈移動,滑鼠經過暫停,點擊關閉按鈕移除。本文提供完整原生 JS 實現,邏輯清晰,易於擴展。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>飛動廣告</title>
<style>
body, div, p { margin: 0; padding: 0; font-size: 14px; }
#divMain { width: 200px; height: 800px; } /* 長頁面提供滾動空間 */
#divFly {
position: absolute; top: 0; left: 0; border: 1px solid green;
cursor: move; z-index: 9999;
}
#divFly img { display: block; }
#divFly p { text-align: right; padding: 4px; background: #fff; border-top: 1px solid #ccc; }
</style>
</head>
<body>
<div id="divMain"></div> <!-- 頁面內容佔位 -->
<div id="divFly">
<img src="../images/fly.gif" width="60" height="60" alt="廣告" />
<p><a href="javascript:void(0)" onclick="closeAD()">關閉</a></p>
</div>
<script>
var tmrID, xDir = 1, yDir = 1;
var flyEl = document.getElementById('divFly');
function moveAD() {
var maxX = document.body.clientWidth - flyEl.offsetWidth;
var maxY = document.body.clientHeight - flyEl.offsetHeight;
var newX = parseInt(flyEl.style.left) + xDir * 5;
var newY = parseInt(flyEl.style.top) + yDir * 5;
if (newX >= maxX) { newX = maxX; xDir = -1; }
if (newX <= 0) { newX = 0; xDir = 1; }
if (newY >= maxY) { newY = maxY; yDir = -1; }
if (newY <= 0) { newY = 0; yDir = 1; }
flyEl.style.left = newX + 'px';
flyEl.style.top = newY + 'px';
}
function fly() { tmrID = setInterval(moveAD, 20); }
function ClearTimer() { clearInterval(tmrID); }
function closeAD() { ClearTimer(); flyEl.style.display = 'none'; }
// 滑鼠互動
flyEl.onmouseover = ClearTimer;
flyEl.onmouseout = fly;
// 啟動
window.onload = fly;
</script>
</body>
</html>
position: absolute 絕對定位,初始 top:0; left:0。setInterval(moveAD, 20) 每 20ms 更新位置,速度 5px。document.body.clientWidth/Height 與元素 offsetWidth/Height 計算可移動最大範圍,超出則反向 (xDir/yDir 乘 -1)。onmouseover 清除計時器,onmouseout 重啟。display: none 隱藏元素。window.innerWidth/Height + scrollX/Y 計算邊界,支援頁面滾動時廣告仍在可視區飛動。setInterval,效能更好、幀率穩定。localStorage.setItem('adClosed', Date.now()),下次不再顯示。mousedown/move/up 讓用戶可拖拽廣告位置。resize 事件重新計算邊界。@keyframes flyAround {
0% { transform: translate(0, 0); }
25% { transform: translate(calc(100vw - 60px), 0); }
50% { transform: translate(calc(100vw - 60px), calc(100vh - 60px)); }
75% { transform: translate(0, calc(100vh - 60px)); }
100% { transform: translate(0, 0); }
}
#divFly {
position: fixed; top: 0; left: 0; width: 60px; height: 60px;
animation: flyAround 20s linear infinite;
pointer-events: none; /* 僅展示,不互動 */
}
#divFly:hover { animation-play-state: paused; }
純 CSS 實現飛動,無 JS 開銷,但互動性受限 (無法點擊關閉、拖拽)。視需求選擇。
JS 飛動廣告展示了定時器動畫、邊界碰撞檢測、滑鼠互動控制的基礎技巧。現代開發中廣告多由廣告聯盟 SDK 或框架組件處理,但理解底層原理有助於自定義互動廣告或教學演示。