function DivFlying() {
var div = document.getElementById("divFly");
if (!div) return;
var intX = window.event.clientX;
var intY = window.event.clientY;
div.style.left = intX + "px";
div.style.top = intY + "px";
}
document.onmousemove = DivFlying;
<div id="divFly" style="position:absolute;">
<img src="fly.gif" /><br />
低調的跟著鼠標飄過~~
</div>
document.onmousemove 監聽全局滑鼠移動。window.event.clientX/Y 獲取視口座標(IE 事件模型)。position:absolute,設置 left/top 實時跟隨。mousemove 高頻觸發,建議節流或用 requestAnimationFrame。const flyer = document.getElementById('divFly');
let rafId = null;
document.addEventListener('mousemove', e => {
if (rafId) return; // 簡易節流
rafId = requestAnimationFrame(() => {
flyer.style.transform = `translate(${e.clientX}px, ${e.clientY}px)`;
rafId = null;
});
});
改進:transform: translate 啟用 GPU 加速、requestAnimationFrame 對齊幂率、addEventListener 標準事件模型。
requestAnimationFrame 循環插值當前位置向目標位置靠近。cursor: url(cursor.png), auto 替換系統游標。mousedown/mousemove/mouseup 實現拖放。自定義游標、工具提示跟隨、拖拽預覽、遊戲準星、視差特效背景層跟隨。