MouseEvent: screenX 屬性

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

MouseEvent 介面的只讀屬性 screenX 提供滑鼠指標在 螢幕座標中的水平座標(偏移量)。

注意: 在多螢幕環境中,水平對齊的螢幕將被視為一個裝置,因此 screenX 值的範圍將擴充套件到螢幕的總寬度。

以畫素為單位的 double 浮點數值。

早期規範版本將其定義為指向畫素數量的整數。

示例

此示例顯示了每次觸發 mousemove 事件時滑鼠的座標。

HTML

html
<p>Move your mouse to see its position.</p>
<p id="screen-log"></p>

JavaScript

js
let screenLog = document.querySelector("#screen-log");
document.addEventListener("mousemove", logKey);

function logKey(e) {
  screenLog.innerText = `
    Screen X/Y: ${e.screenX}, ${e.screenY}
    Client X/Y: ${e.clientX}, ${e.clientY}`;
}

結果

事件路由

當您在 window、document 或其他寬敞的元素上捕獲事件時,您可以獲取該事件(例如點選)的座標並進行適當的路由,如下例所示:

js
function checkClickMap(e) {
  if (e.screenX < 50) doRedButton();
  if (50 <= e.screenX && e.screenX < 100) doYellowButton();
  if (e.screenX >= 100) doRedButton();
}

規範

規範
UI 事件
# dom-mouseevent-screenx

瀏覽器相容性

另見