Window:screenTop 屬性

Baseline 廣泛可用 *

此功能已成熟,並可在許多裝置和瀏覽器版本上執行。自 2018 年 12 月起,所有瀏覽器均支援此功能。

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

Window.screenTop 只讀屬性返回使用者瀏覽器視口頂部邊框到螢幕頂部之間的垂直距離(以 CSS 畫素為單位)。

注意: screenTop 是舊的 Window.screenY 屬性的別名。screenTop 最初僅在 IE 中支援,但由於其受歡迎程度,後來被引入到所有瀏覽器中。

一個數值,等於瀏覽器視口頂部邊緣到螢幕頂部邊緣之間的 CSS 畫素數量。

示例

在我們 screenleft-screentop 示例中,您會看到一個繪製了圓形的 canvas。在此示例中,我們使用 screenLeft/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);

在程式碼中,我們還包含了一個程式碼片段,用於檢測是否支援 screenLeft,如果不支援,則使用 Window.screenX/ Window.screenYscreenLeft/screenTop 提供 polyfill。

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

規範

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

瀏覽器相容性

另見