getBoundingClientRect изнутри iFrame - PullRequest
0 голосов
/ 30 октября 2018

У меня есть функция для оценки того, находится ли элемент (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;
}

Эта функция работает правильно, когда она обслуживается непосредственно на странице, но в реальной среде, когда эта функция запускается, она находится внутри iFrame, и похоже, что getBoundingClientRect() ссылается на область просмотра iFrame, а не на главное окно?

Есть ли способ использовать окно просмотра главного окна из iFrame с getBoundingClientRect()

1 Ответ

0 голосов
/ 20 декабря 2018

Каждый iframe имеет свою собственную область видимости, поэтому окно внутри iframe отличается от окна root .

Вы можете получить корневое окно на window.top, и с этим знанием вы можете рассчитать абсолютную позицию текущего фрейма. Вот правильная функция:

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 измените эти строки:

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

до

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

и это должно работать.

...