问题描述
我有一个函数来评估某个元素(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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!