通常、これは簡単ですが、視覚的な理由から、iframe をそれに含まれるコンテンツと同じ高さに強制します。これが行うことは、親ウィンドウのスクロール バーであるスクロール バーを 1 つだけ表示することです。iframe ドキュメントはスクロールしません。問題は、iframe 内で div を中央に配置しようとすると発生します。ページが数ページ下にスクロールされると、正確なスクロールトップの値を取得できません。$(window).scrollTop() は常にゼロです。$(window).scrollTop() の代わりにparent.document.documentElement.scrollTopを使用すると、値を取得できますが、完全に昼食になります。たとえば、iframe の高さが 2011 で、iframe の一番下までスクロールして、parent.document.documentElement.scrollTop を照会すると、値 567 が返されます。私の画面サイズは1200です
すべてのブラウザーで同じ結果が得られます。最新の IE、FF、Opera、Chrome をテスト済み。
シミュレートする
in outerdoc.htm I have
<iframe id="myFrame" src="doc1.htm"></iframe>
doc1.htm:
<html>
<head>
<title>my title</title>
</head>
<body>
<p> 10 pages of content near the bottom <div onclick="CenterDiv($('#myDiv'))">show div</div></P>
<div id="myDiv"></div>
<script type="text/javascript" language="javascript">
$(document).ready(function()
{
$('#myFrame', top.document).height($(document).height()); //sets height of frame to document within
});
function CenterDiv(item)
{
var mtop = ($(window).height() / 2 - item.height() / 2) + $(top.window).scrollTop());
item.css('top', mtop < 0 ? 0 : mtop );
}
</script>
</body>
</html>