浮動式廣告常見於老派入口網站。本文示範如何用原生 JS 建立一個 position:absolute 的浮層,讓它持續貼近滑鼠座標,並在右上角提供關閉按鈕。
<!DOCTYPE html>
<html>
<head>
<title>跟隨滑鼠移動且可關閉的圖片廣告</title>
<meta http-equiv="content-type" content="text/html;charset=gb2312">
</head>
<body>
<script type="text/javascript">
//<![CDATA[
function badAD(html) {
var ad = document.body.appendChild(document.createElement('div'));
ad.style.cssText = "border:1px solid #000;background:#FFF;position:absolute;" +
"padding:24px 4px 4px 4px;font:12px/1.5 verdana;";
ad.innerHTML = html || 'This is bad idea!';
// 右上角關閉鈕
var c = ad.appendChild(document.createElement('span'));
c.innerHTML = "×";
c.style.cssText = "position:absolute;right:2px;top:2px;cursor:pointer";
c.onclick = function () {
document.onmousemove = null; // 停止追蹤
this.parentNode.style.left = '-99999px'; // 移出視線
};
// 用 120ms 節流,避免滑鼠移動過於頻繁
document.onmousemove = function (e) {
e = e || window.event;
var x = e.clientX, y = e.clientY;
setTimeout(function () {
if (ad.hover) return; // 滑鼠在廣告上就不動
ad.style.left = x + 5 + 'px';
ad.style.top = y + 5 + 'px';
}, 120);
};
ad.onmouseover = function () { this.hover = true; };
ad.onmouseout = function () { this.hover = false; };
}
badAD('<img src="/images/m02.jpg">')
//]]>
</script>
</body>
</html>
onmousemove 觸發頻率極高,直接改 style 會造成大量重排。用 setTimeout 延遲 120ms 再套用座標,就能大幅降低渲染壓力。
用 hover 旗標記錄滑鼠是否停在廣告上。使用者想點擊或閱讀時,廣告不會亂跑,這是體驗上的關鍵細節。
關閉時把 document.onmousemove 設為 null,否則即使看不見廣告,全域的移動監聽仍在消耗效能。
現代做法會改用 position:fixed 讓浮層不受頁面捲動影響,並搭配 requestAnimationFrame 取代 setTimeout 以取得更平順的追蹤。另外提醒:過度干擾閱讀的浮動廣告會被瀏覽器列為侵入式內容,實際專案上建議保留明確的關閉入口並避免遮擋主要操作區。