Control iframe height with jQuery

后端 未结 9 1761
情书的邮戳
情书的邮戳 2020-12-13 07:32

I am using jQuery to control the height of an iframe.

jQuery(\"iframe\",top.document).contents().height();  

This works when the height of

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 07:37

    This is ancient but hopefully it helps.

    Seems like Chrome (or maybe all of webkit, not sure) has a bug where the scrollHeight can increase but not decrease (at least in the case of content in an iframe). So if the content grows, then shrinks, the scrollOffset stays at the higher level. That's not very nice when you are attempting to make the iframe's height just big enough for it's ever-changing content.

    A hack workaround is to make it recalculate the height by setting the height to something definitely small enough to cause the iframe's height to be smaller than it's content, then the scrollHeight is reset.

    var frame = top.document.getElementById('iFrameParentContainer').getElementsByTagName('iframe')[0];
    var body = frame.contentWindow.document.body;
    var height = body.scrollHeight; // possibly incorrect
    body.height = "1px";
    height = body.scrollHeight; // correct
    

    This can cause a slight flicker but normally doesn't, at least, it works on my machine (tm).

提交回复
热议问题