一個含圖片的 `
浮動廣告示範
class FloatAdManager {
constructor() { this.ads = []; this.animate = this.animate.bind(this); }
add(element, {width, height}) {
const ad = { el: element, w: width, h: height,
x: Math.random()*(innerWidth-width), y: Math.random()*(innerHeight-height),
vx: (Math.random()-0.5)*4+1, vy: (Math.random()-0.5)*4+1, paused: false };
this.ads.push(ad);
if (this.ads.length === 1) requestAnimationFrame(this.animate);
}
animate() {
for (const ad of this.ads) {
if (ad.paused) continue;
// 邊界反彈
if (ad.x <= 0 || ad.x >= innerWidth - ad.w) ad.vx = -ad.vx;
if (ad.y <= 0 || ad.y >= innerHeight - ad.h) ad.vy = -ad.vy;
ad.x += ad.vx; ad.y += ad.vy;
ad.el.style.transform = `translate(${ad.x}px, ${ad.y}px)`;
// 簡易碰撞檢測 (可選)
}
requestAnimationFrame(this.animate);
}
}
let dragging = false, startX, startY, startAdX, startAdY;
ad.addEventListener('touchstart', e => {
dragging = true;
startX = e.touches[0].clientX; startY = e.touches[0].clientY;
startAdX = x; startAdY = y;
paused = true;
}, {passive: true});
window.addEventListener('touchmove', e => {
if (!dragging) return;
x = startAdX + e.touches[0].clientX - startX;
y = startAdY + e.touches[0].clientY - startY;
// 夾持邊界
x = Math.max(0, Math.min(x, maxX));
y = Math.max(0, Math.min(y, maxY));
ad.style.transform = `translate(${x}px, ${y}px)`;
}, {passive: true});
window.addEventListener('touchend', () => { dragging = false; paused = false; });
const CLOSED_KEY = 'floatAdClosed';
if (localStorage.getItem(CLOSED_KEY)) ad.style.display = 'none';
function stopFloat() { ad.style.display = 'none'; localStorage.setItem(CLOSED_KEY, '1'); }
// 可加「不再顯示」勾選框、過期時間等邏輯
純原生 JS 實作漂浮廣告極其輕量 (壓縮 < 1KB),掌握 `requestAnimationFrame` + `transform` + 邊界反彈核心模式,可輕鬆擴充拖曳、碰撞、多實例管理等進階互動。