从 iFrame 中 getBoundingClientRect

Jon*_*eux 4 javascript iframe cross-domain getboundingclientrect

我有一个函数来评估一个元素(一个 iFrame)是否在视口内,如果该元素在视图中它返回 true。

function isElementInViewport() {
    var el = document.getElementById('postbid_if')
    var rect = el.getBoundingClientRect();
    var elemTop = rect.top;
    var elemBottom = rect.bottom;

    console.log("eleTom " + elemTop)
    console.log("elemBottom " + elemBottom)
    console.log("window.innerHeight " + (window.innerHeight + (window.top.innerHeight * 0.5)))

    var isVisible = (elemTop >= 0) && (elemBottom <= (window.innerHeight + window.innerHeight * 0.5));
    return isVisible;
}
Run Code Online (Sandbox Code Playgroud)

当直接在页面上提供时,此函数可以正常工作,但在实时环境中,当此函数运行时,它位于 iFrame 内,并且看起来像是getBoundingClientRect()在引用 iFrame 的视口而不是主窗口?

有什么方法可以在 iFrame 中使用主窗口视口 getBoundingClientRect()

paw*_*ina 8

每个 iframe 都有自己的作用域,因此 iframe 内的窗口与窗口不同。

您可以通过window.top并根据这些知识获得根窗口,您可以计算当前 iframe 的绝对位置。这是一个适当的功能:

function currentFrameAbsolutePosition() {
  let currentWindow = window;
  let currentParentWindow;
  let positions = [];
  let rect;

  while (currentWindow !== window.top) {
    currentParentWindow = currentWindow.parent;
    for (let idx = 0; idx < currentParentWindow.frames.length; idx++)
      if (currentParentWindow.frames[idx] === currentWindow) {
        for (let frameElement of currentParentWindow.document.getElementsByTagName('iframe')) {
          if (frameElement.contentWindow === currentWindow) {
            rect = frameElement.getBoundingClientRect();
            positions.push({x: rect.x, y: rect.y});
          }
        }
        currentWindow = currentParentWindow;
        break;
      }
  }
  return positions.reduce((accumulator, currentValue) => {
    return {
      x: accumulator.x + currentValue.x,
      y: accumulator.y + currentValue.y
    };
  }, { x: 0, y: 0 });
}
Run Code Online (Sandbox Code Playgroud)

现在里面isElementInViewport改变这些行:

var elemTop = rect.top;
var elemBottom = rect.bottom;
Run Code Online (Sandbox Code Playgroud)

var currentFramePosition = getCurrentFrameAbsolutePosition();
var elemTop = rect.top + currentFramePosition.y;
var elemBottom = rect.bottom + currentFramePosition.y;
Run Code Online (Sandbox Code Playgroud)

这应该有效。

  • ofc,这不包括安全框架,因为您无权访问父窗口 (2认同)