如何使用 JavaScript 獲取游標相對於螢幕的座標?


在本教程中,我們將學習如何使用 JavaScript 獲取滑鼠游標相對於螢幕的座標。我們將找到游標相對於螢幕的垂直(Y 軸)和水平(X 軸)位置。

JavaScript 允許我們使用兩種不同的屬性來獲取滑鼠游標相對於螢幕的座標,當滑鼠按鈕在螢幕上的任何位置按下時:

  • 使用 event.screenX 屬性
  • 使用 event.screenY 屬性

讓我們逐一結合程式碼示例來討論它們。

使用 event.screenX 屬性

event.screenX 屬性用於獲取 X 軸或游標水平位置的座標,即它在螢幕上單擊的位置。它將返回一個表示游標水平位置的數值。

語法

以下語法將展示如何使用 event.screenX 獲取 X 座標或水平位置:

function function_name(event){
   let X=event.screenX;
}

步驟

  • 步驟 1 - 在第一步中,我們將為事件宣告回撥函式,該函式將在事件觸發時呼叫。
  • 步驟 2 - 在下一步中,我們必須宣告一個變數並使用event.screenX屬性為其賦值,該屬性儲存事件觸發或單擊事件發生時 X 座標的值。
  • 步驟 3 - 在第三步中,我們顯示了儲存在上一步中宣告的變數中的游標 X 座標的值。

示例

以下示例將說明如何使用 event.screenX 屬性獲取單擊位置的游標 X 座標。

<!DOCTYPE html> <html onclick="display(event)"> <body> <h3>Find the coordinates of the cursor relative to the screen</h3> <p id="para">Click anywhere on the screen to see X coordinate of the cursor.</p> <p id="result"></p> <script> function display(event) { let x = event.screenX; let result = document.getElementById("result"); result.innerHTML = "<b>X-coordinate: </b>" + x; } </script> </body> </html>

在上面的示例中,我們在 HTML 文件的元素上使用了onclick事件,以便我們能夠在螢幕上的任何位置單擊並獲取游標的水平位置或 X 座標值,即事件觸發或單擊發生的位置。

使用 event.screenY 屬性

它用於獲取游標的垂直位置或 Y 軸座標,即游標單擊或事件觸發的位置。與 event.screenX 類似,它也返回一個表示游標垂直位置的數值。

語法

以下語法將允許您獲取游標單擊位置的 Y 座標或垂直位置。

function function_name(event){
   let Y=event.screenY;
}

步驟

  • 步驟 1 - 在第一步中,我們將為事件宣告回撥函式,該函式將在事件觸發時呼叫。
  • 步驟 2 - 在下一步中,我們必須宣告一個變數並使用event.screenY為其賦值,該屬性儲存事件觸發或單擊事件發生時 Y 座標的值。
  • 步驟 3 - 在第三步中,我們顯示了儲存在上一步中新宣告的變數中的游標 Y 座標的值。

示例

<!DOCTYPE html> <html onclick="display(event)"> <body> <h3>Find the coordinates of the cursor relative to the screen</h3> <p id="para">Click anywhere on the screen to see Y-coordinate of the cursor.</p> <p id="result"></p> <script> function display(event) { let Y = event.screenY; let result = document.getElementById("result"); result.innerHTML = "<b>Y-coordinate: </b>" + Y; } </script> </body> </html>

在上面的示例中,我們在 HTML 文件的元素 (html) 上使用了onclick事件,以便我們能夠在螢幕上的任何位置單擊並獲取游標的垂直位置或 Y 座標,即事件觸發或單擊發生的位置。

讓我們看看如何同時使用這兩個屬性來獲取 X 和 Y 座標或游標的水平和垂直位置。

步驟

  • 步驟 1 - 在第一步中,我們將為事件宣告回撥函式,該函式將在事件觸發時呼叫。
  • 步驟 2 - 在下一步中,我們必須宣告兩個變數並分別使用event.screenXevent.screenY為其賦值,這兩個屬性分別儲存事件觸發或單擊事件發生時 X 座標和 Y 座標的值。
  • 步驟 3 - 在第三步中,我們顯示了儲存在上一步中宣告的變數中的游標 X 座標和 Y 座標的值。

示例

以下示例將顯示游標的 X 和 Y 軸座標:

<!DOCTYPE html> <html onclick="display(event)"> <body> <h3>Find the coordinates of the cursor relative to the screen</h3> <p id="para">Click anywhere on the screen to see X and Y-coordinate of the cursor using JavaScript properties.</p> <p id="result"></p> <script> function display(event) { let X = event.screenX; let Y = event.screenY; let result = document.getElementById("result"); result.innerHTML = "<b>X-coordinate: </b>" + X + "<br><b>Ycoordinate: </b>: " + Y; } </script> </body> </html>

同樣,在這個示例中,我們在HTML元素上使用了事件來獲取單擊事件的全域性訪問許可權,以便在螢幕上的任何位置單擊。

在本教程中,我們瞭解了兩個用於獲取游標相對於螢幕的座標的屬性,並透過單獨的程式碼示例以及整合示例(其中我們使用了這兩個屬性來獲取游標相對於螢幕的垂直和水平位置)討論了它們。

更新於: 2022-10-31

4K+ 閱讀量

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告