LayoutShiftAttribution

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

LayoutShiftAttribution 介面提供了有關已發生佈局移位的元素的除錯資訊。

透過呼叫 LayoutShift.sources 返回的陣列中包含 LayoutShiftAttribution 的例項。

例項屬性

LayoutShiftAttribution.node 只讀 實驗性

返回已發生移位的元素(如果已被移除則為 null)。

LayoutShiftAttribution.previousRect 只讀 實驗性

返回一個 DOMRectReadOnly 物件,表示移位前元素的位置。

LayoutShiftAttribution.currentRect 只讀 實驗性

返回一個 DOMRectReadOnly 物件,表示移位後元素的位置。

例項方法

LayoutShiftAttribution.toJSON() 實驗性

返回 LayoutShiftAttribution 物件的 JSON 表示形式。

示例

以下示例找到具有最高佈局移位分數的元素,並返回該條目中移位前尺寸最大的元素(previousRect)。有關更多詳細資訊,請參閱 Debug Web Vitals in the field

js
function getCLSDebugTarget(entries) {
  const largestEntry = entries.reduce((a, b) =>
    a && a.value > b.value ? a : b,
  );
  if (largestEntry?.sources?.length) {
    const largestSource = largestEntry.sources.reduce((a, b) => {
      const area = (el) => el.previousRect.width * el.previousRect.height;
      return a.node && area(a) > area(b) ? a : b;
    });
    if (largestSource) {
      return largestSource.node;
    }
  }
}

規範

規範
佈局不穩定 API
# sec-layout-shift-attribution

瀏覽器相容性

另見