移動滑鼠即可看到座標即時更新。原理很簡單:監聽 document 的 mousemove 事件,從事件物件取出 pageX 與 pageY,再寫進頁面上的容器。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JQ獲得鼠標位置-</title>
<script type="text/javascript" src="https:///keleyi/pmedia/jquery/jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="mousePosition_keleyi_com" style="border:1px solid silver;width:219px;height:23px"></div>
<script type="text/javascript">
$(document).mousemove(function (e) {
var xy_keleyi_com = "x坐標:" + e.pageX + ",y坐標:" + e.pageY;
$("#mousePosition_keleyi_com").text(xy_keleyi_com);
})
</script>
</body>
</html>
選錯座標系是這類效果跑位的常見原因。另外,mousemove 觸發頻率極高,若要在裡面做重運算或 DOM 大量更新,記得加上節流(throttle)。
原文:https:///a/bjac/8p1g5yeq.htm