首页 文章

iFrame - iFrame中内容更改的自动高度

提问于
浏览
4

我有以下代码: -

<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的高度?

Note: iFrame与iFrame src显示在同一个域中 .

2 回答

  • 0

    试试这个 . 不需要Jquery,但是当内容更改时,您将不得不调用resizeIframe .

    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

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

    SO Explanation

相关问题