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

浏览器兼容性

另见