开发者

jQuery/javascript - Center a div within an iframe view area. scrollTop not accurate with iframe height adjusted

ok normally this would be easy but for visual reasons I force my iframe to be the same height as the content it contains. What this does is gives me only one scroll bar, the scroll bar on the parent window. The iframe document never scrolls. The problem comes when i try to center a div within the iframe. When the page is scrolled a couple of pages down I cannot get an accurate scrolltop value. $(window).scrollTop() is always zero. If I use parent.document.documentElement.scrollTop instead of $(window).scrollTop() I get a value but it is completely out to lunch. For example if iframe's height is 2011 and I scroll to the bottom of the iframe and I query parent.document.documentElement.scrollTop I get a value 567 returned. My screen size is 1200

Same results in all browsers. Tested latest IE, FF, Opera, Chrome.

To simulate

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"></di开发者_C百科v>
  <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>


I could not get this resolved but I figure I would write what I did to work around this. I put the div I wanted centered on the page that holds the iframe as well as the centerdiv function. Then in the my code inside the iframe I did the following.

function CenterDiv(item)
{
if (window.location != window.parent.location) parent.CenterDiv(item);      
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜