从iFrame中获取getBoundingClientRect [英] getBoundingClientRect from within iFrame

查看:648
本文介绍了从iFrame中获取getBoundingClientRect的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a function to assess whether an element (an iFrame) is within the viewport if the element is in view it returns 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;
}

直接在页面上投放时此功能可以正常工作,但是在实时环境中运行此功能时,该功能位于iFrame内部,看起来getBoundingClientRect()引用的是iFrame的视口而不是主窗口?

This function works correctly when served directly on the page, but in the live environment when this function runs it's inside an iFrame and it looks like getBoundingClientRect() is referencing the viewport of the iFrame rather than the main window?

是否可以通过getBoundingClientRect()

推荐答案

每个iframe都有自己的作用域,因此iframe中的窗口不同于 root 窗口.

Each iframe has his own scope so window inside iframe is different than the root window.

您可以通过window.top来获取根窗口,并以此为基础可以计算当前iframe的绝对位置.这是一个适当的功能:

You can get root window by window.top and with that knowledge you could calculate absolute position of current iframe. Here is a proper function:

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 });
}

现在在isElementInViewport内部,更改以下行:

Now inside isElementInViewport change these lines:

var elemTop = rect.top;
var elemBottom = rect.bottom;

var currentFramePosition = getCurrentFrameAbsolutePosition();
var elemTop = rect.top + currentFramePosition.y;
var elemBottom = rect.bottom + currentFramePosition.y;

这应该可行.

这篇关于从iFrame中获取getBoundingClientRect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆