Window:screenX 屬性

Baseline 廣泛可用 *

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

* 此特性的某些部分可能存在不同級別的支援。

Window.screenX 只讀屬性返回使用者瀏覽器視口左邊框到螢幕左側的水平距離(以 CSS 畫素為單位)。

注意: 近期,現代瀏覽器實現了一個 screenX 的別名 — Window.screenLeft。此屬性最初僅在 IE 中受支援,但由於其受歡迎程度,現已推廣到所有瀏覽器。

一個數字,表示從瀏覽器視口左邊緣到螢幕左邊緣的 CSS 畫素數量。

示例

在我們的 screenleft-screentop原始碼)示例中,您將看到一個繪製有圓形的 canvas。在此示例中,我們使用 Window.screenLeft/ Window.screenTop 結合 Window.requestAnimationFrame() 來不斷地在螢幕的物理位置上重繪圓形,即使視窗位置發生移動。

js
initialLeft = window.screenLeft + canvasElem.offsetLeft;
initialTop = window.screenTop + canvasElem.offsetTop;

function positionElem() {
  let newLeft = window.screenLeft + canvasElem.offsetLeft;
  let newTop = window.screenTop + canvasElem.offsetTop;

  let leftUpdate = initialLeft - newLeft;
  let topUpdate = initialTop - newTop;

  ctx.fillStyle = "rgb(0 0 0)";
  ctx.fillRect(0, 0, width, height);
  ctx.fillStyle = "rgb(0 0 255)";
  ctx.beginPath();
  ctx.arc(
    leftUpdate + width / 2,
    topUpdate + height / 2 + 35,
    50,
    degToRad(0),
    degToRad(360),
    false,
  );
  ctx.fill();

  pElem.textContent = `Window.screenLeft: ${window.screenLeft}, Window.screenTop: ${window.screenTop}`;

  window.requestAnimationFrame(positionElem);
}

window.requestAnimationFrame(positionElem);

這些屬性的工作方式與 screenX/screenY 完全相同。

在程式碼中,我們還包含了一個程式碼片段,用於檢測是否支援 screenLeft,如果不支援,則使用 screenX/screenY 來填充 screenLeft/screenTop

js
if (!window.screenLeft) {
  window.screenLeft = window.screenX;
  window.screenTop = window.screenY;
}

規範

規範
CSSOM 檢視模組
# dom-window-screenx

瀏覽器相容性

另見