DIV CSS 佈局教程網

用JS在網頁中實時獲取並顯示鼠標坐標的方法
編輯:關於JavaScript     

本文為大家介紹一個基礎但實用的小功能:在網頁上實時顯示鼠標當前所在的 X、Y 坐標。它在做拖拽、繪圖、選取區域等交互時經常用到。

實現思路

核心是監聽鼠標的移動事件,並從事件對象中讀取坐標值。這段代碼兼容了兩類瀏覽器:在 Netscape 中通過 captureEvents 捕獲事件、從事件對象的 screenX/screenY 取屏幕坐標;在 IE 中則通過 window.event 的 x/y 取值。無論哪種,最終都把結果寫入頁面上的兩個輸入框實時展示。

完整代碼如下:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>顯示鼠標坐標</title>
</head>
<body onMousemove="micro$oftMouseMove()">
<SCRIPT LANGUAGE="JavaScript">
if (navigator.appName == 'Netscape')
{
document.captureEvents(Event.MOUSEMOVE);
document.onmousemove = netscapeMouseMove;
}
function netscapeMouseMove(e) {
if (e.screenX != document.test.x.value && e.screenY != document.test.y.value);
{
document.test.x.value = e.screenX;
document.test.y.value = e.screenY;
}
}
function micro$oftMouseMove() {
if (window.event.x != document.test.x.value && window.event.y != document.test.y.value);
{
document.test.x.value = window.event.x;
document.test.y.value = window.event.y;
}
}
</SCRIPT>
<FORM NAME="test">
X: <INPUT TYPE="TEXT" NAME="x" SIZE="4">
Y: <INPUT TYPUE="TEXT" NAME="y" SIZE="4">
</FORM>
</body>
</html>

以上就是本次分享的全部內容,希望對大家的 JavaScript 開發有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved