代码之家  ›  专栏  ›  技术社区  ›  nsilva

iFrame-iFrame内内容更改时自动高度

  •  4
  • nsilva  · 技术社区  · 10 年前

    我有以下代码:-

    <script language="javascript" type="text/javascript">
      function resizeIframe(obj) {
        obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
      }
    </script>
    
    <div class="resizable">
        <iframe src="http://yellow-taxi.co.uk/onlinebooking/index.php" frameborder="0" width="100%" height="100%" scrolling="no" onload="resizeIframe(this)"></iframe>
    </div>
    

    Javascript会将高度调整为iFrame的初始高度,但在预订过程中,iFrame高度会增加。有没有一种方法可以在内容更改时根据其内部的内容自动调整iFrame的高度?

    注: iFrame显示在与iFrame src相同的域中。

    2 回复  |  直到 10 年前
        1
  •  2
  •   Ageonix    8 年前

    试试这个。不需要Jquery,但当内容更改时,您必须调用resizeFrame。

    function resizeIframe(obj) {
        var newheight;
        var newwidth;
    
        if(document.getElementById){
            newheight = document.getElementById(obj).contentWindow.document .body.scrollHeight;
            newwidth = document.getElementById(obj).contentWindow.document .body.scrollWidth;
        }
    
        document.getElementById(obj).height = (newheight) + "px";
        document.getElementById(obj).width = (newwidth) + "px";
    }
    

    下面是一个示例iFrame及其必要的属性。请确保使用您的iFrame名称调用上述方法。

    <iframe src="yourpage.htm" width="100%" height="300px" id="yourIframe" marginheight="0" frameborder="0" onLoad="resizeIframe('yourIframe');"></iframe>
    

    还有一个很好的JQuery插件可以完成这项任务,并且可以在域上工作: https://github.com/house9/jquery-iframe-auto-height

        2
  •  0
  •   Community Mohan Dere    9 年前

    长话短说,你不能,除非你的页面与iframe页面位于同一个域。您遇到了跨域限制,作为浏览器设置的安全措施,您将无法访问该iframe内容中的JS、DOM元素或属性。

    SO Explanation