这最终是一个比代码更多的研究。发生的事情是-我有代码可以根据内容调整iframe的大小。
在所有其他浏览器中,这都可以正常工作,并消除滚动条。原来是野生动物
automatically sizes the Iframe
留下它自己的卷轴。在我的应用程序中,没有静态页面。这使我面临无法使用
scrolling=no
链接中描述的修复。
在发现了到底发生了什么之后,我采取了另一种方法来解决
elm.scrollIntoView()
. 代码更多的是注释,除了重要的部分;
-
检测何时应用iframe修复
RequiresIframeScrollFix
-
使用
elm.getBoundingClientRect().top
从iframe中获取滚动位置。
-
与要滚动的父级通信
window.parent.postMessage
-
在父级中接收消息
window.addEventListener('message',...)
这就是它的样子。
iFrAME站点
我们的iframe站点当前将其元素滚动到如下视图中
elm.scrollIntoView();
我们已将其更改为以下内容。
if (RequiresIframeScrollFix())
window.parent.postMessage(elm.getBoundingClientRect().top, "*"); // Tell IFrame parent to do the scrolling. If this is not a test environment, replace "*" with the parent domain.
else
elm.scrollIntoView(); // If not scroll into view as usual.
可选:修复iOS iframes中的引导模式定位,使用
elm.getboundingclientrect().top
.
$('#modalId').css('top', elm.getBoundingClientRect().top); // This fixes modal not in view on Safari Iframes.
RequiresIframeScrollFix()
主要是由一些很好的文档代码组成,用来确定我们是在ipad还是iphone上使用iframe。
var debugNavigator = false;
function RequiresIframeScrollFix() {
try {
if (debugNavigator)
alert(navigator.userAgent);
var is_safari = navigator.userAgent.indexOf("Safari") > -1;
var is_chrome = navigator.userAgent.indexOf('Chrome') > -1;
if ((is_chrome) && (is_safari)) { is_safari = false; }
if (is_safari && inIframe() && (
navigator.userAgent.match(/iPad/i) ||
navigator.userAgent.match(/iPhone/i)
))
return true;
else
return false;
} catch (e) {
alert(e.message);
}
}
function inIframe() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
父网站
我们的父站点包含Safari Mobile自动调整大小的iframe。因此,父站点现在有自己的滚动条,而不是iframe。我们将监听器设置在父站点内,以便在它接收到来自iframed站点的消息时自动滚动。
window.onload = function () {
function receiveMessage(e) {
try {
window.scrollTo(0, e.data);
}
catch (err) {
}
}
window.addEventListener('message', receiveMessage);
}
希望这能帮助其他人在手机上分析Safari iFrame问题。另外,如果我忽略了一个更好的解决方案,请告诉我。