網頁上「圖片跟著滑鼠跑」的效果看起來神奇,實際原理相當單純:只要持續監聽滑鼠移動事件,把游標的座標寫進元素的定位樣式即可。以下用 jQuery 完成一個可直接跑起來的示範。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>滑鼠拖曳圖片</title>
<script type="text/javascript" src="jquery-1.4.4.js"></script>
<script type="text/javascript">
$(function () {
$("html").mousemove(function (e) {
$("#a").css("left", e.pageX).css("top", e.pageY);
});
});
</script>
<style type="text/css">
.a {
width: 200px;
height: 100px;
position: absolute;
background-color: rgb(0, 0, 0);
}
</style>
</head>
<body>
<img src="圖片" id="a" name="a" class="a" />
</body>
</html>
整個效果的核心是 mousemove 事件中的 e.pageX 與 e.pageY,它們代表游標相對於整個頁面的座標。把這組數值寫進 left 與 top,圖片就會貼著游標移動。
另外別忘了 CSS 裡的 position: absolute。少了它,left 與 top 完全不會生效,這是初學時最容易卡住的地方。
這個範例是「圖片永遠黏在游標上」,並非按住才拖動。若要做出符合直覺的拖曳行為,還需要補上 mousedown 記錄起始位置與滑鼠偏移量,並在 mouseup 時解除移動監聽,同時加上邊界判斷避免圖片被拖出視窗。