我有一个函数来评估元素(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的视口而不是主窗口?< / p>
是否可以通过getBoundingClientRect()
在iFrame中使用主窗口视口
答案 0 :(得分:1)
每个iframe都有自己的作用域,因此iframe中的窗口与 root 窗口不同。
您可以通过def start(bot, update):
sub = [
[InlineKeyboardButton("AAA", callback_data='0'),
InlineKeyboardButton("BBB", callback_data='1')]
]
reply_markup = InlineKeyboardMarkup(sub)
update.message.reply_text('Select Branch:', reply_markup=reply_markup)
def button(bot, update):
subK = [
InlineKeyboardButton("JJJ", callback_data='0'),
InlineKeyboardButton("HHH", callback_data='1')
]
reply_markup = InlineKeyboardMarkup(subK)
query = update.callback_query
bot.edit_message_text(chat_id=query.message.chat_id,
message_id=query.message.message_id,
reply_markup=ReplyKeyboardRemove())
bot.edit_message_text(chat_id=query.message.chat_id,
message_id=query.message.message_id,
reply_markup=reply_markup)
来获取根窗口,并以此为基础可以计算当前iframe的绝对位置。这是一个适当的功能:
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;
这应该可行。