首页 文章

根据里面的内容制作iframe高度动态 - JQUERY / Javascript

提问于
浏览
167

我在iframe中加载一个aspx网页 . Iframe中的内容可以比iframe的高度更高 . iframe不应该有滚动条 .

我在iframe中有一个包装器 div 标签,它基本上都是内容 . 我写了一些jQuery来调整大小:

$("#TB_window", window.parent.document).height($("body").height() + 50);

其中 TB_window 是包含 Iframe 的div .

body - iframe中aspx的body标记 .

此脚本附加到iframe内容 . 我从父页面获取 TB_window 元素 . 虽然这在Chrome上运行良好,但TB_window在Firefox中崩溃 . 我真的很困惑/失去了为什么会发生这种情况 .

16 回答

  • 1

    你可以在这里参考相关的问题 - How to make width and height of iframe same as its parent div?

    设置动态高度 -

    • 我们需要与跨域iFrame和父进行通信

    • 然后我们可以将iframe的滚动高度/内容高度发送到父窗口

    和代码 - https://gist.github.com/mohandere/a2e67971858ee2c3999d62e3843889a8

  • -1

    要添加到似乎在底部切断的窗口块,特别是当您没有滚动我使用时:

    function resizeIframe(iframe) {
        var addHeight = 20; //or whatever size is being cut off
        iframe.height = iframe.contentWindow.document.body.scrollHeight + addHeight + "px";
      }
    
  • 0

    对Aristos的回答略有改善......

    <script type="text/javascript">
      function resizeIframe(iframe) {
        iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
      }
    </script>
    

    然后在iframe中声明如下:

    <iframe onload="resizeIframe(this)" ...
    

    有两个小的改进:

    • 您不需要通过document.getElementById获取元素 - 因为您已经在onload回调中使用了它 .

    • 如果're going to reassign it in the very next statement. Doing so actually incurs an overhead as you'处理DOM元素,则无需设置 iframe.height = "" .

  • 183
    jQuery('.home_vidio_img1 img').click(function(){
        video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
        jQuery(this).replaceWith(video);
    });
    
    jQuery('.home_vidio_img2 img').click(function(){
        video = <iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>;
        jQuery('.home_vidio_img1 img').replaceWith(video);
        jQuery('.home_vidio_img1 iframe').replaceWith(video);
    });
    
    jQuery('.home_vidio_img3 img').click(function(){
        video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
        jQuery('.home_vidio_img1 img').replaceWith(video);
        jQuery('.home_vidio_img1 iframe').replaceWith(video);
    });
    
    jQuery('.home_vidio_img4 img').click(function(){
        video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
        jQuery('.home_vidio_img1 img').replaceWith(video);
        jQuery('.home_vidio_img1 iframe').replaceWith(video);
    });
    
  • 90

    当您需要没有jquery的解决方案时,这个很有用 . 在这种情况下,您应该尝试添加容器并以百分比为其设置填充

    HTML示例代码:

    <div class="iframecontainer">
        <iframe scrolling="no" src="..." class="iframeclass"width="999px" height="618px"></iframe>
    </div>
    

    CSS示例代码:

    .iframeclass{
        position: absolute;
        top: 0;
        width: 100%;
    }
    
    .iframecontainer{
        position: relative;
        width: 100%;
        height: auto;
        padding-top: 61%;
    }
    
  • 5

    对BlueFish的回答略有改善......

    function resizeIframe(iframe) {
        var padding = 50;
        if (iframe.contentWindow.document.body.scrollHeight < (window.innerHeight - padding))
            iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
        else
            iframe.height = (window.innerHeight - padding) + "px";
    }
    

    这需要考虑窗口屏幕(浏览器,手机)的高度,这对于响应式设计和具有巨大高度的iframe是有益的 . 填充表示在iframe进入整个屏幕的情况下,iframe上方和下方的填充 .

  • 8

    以防这有助于任何人 . 我试着让它发挥作用,然后我注意到iframe有一个高度为100%的类条目 . 当我删除它时,一切都按预期工作 . 所以,请检查任何css冲突 .

  • 0

    您可以使用以下命令检索 IFRAME 内容的高度: contentWindow.document.body.scrollHeight

    加载 IFRAME 后,您可以通过执行以下操作更改高度:

    <script type="text/javascript">
      function iframeLoaded() {
          var iFrameID = document.getElementById('idIframe');
          if(iFrameID) {
                // here you can make the height, I delete it first, then I make it again
                iFrameID.height = "";
                iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
          }   
      }
    </script>
    

    然后,在 IFRAME 标记上,您可以像这样连接处理程序:

    <iframe id="idIframe" onload="iframeLoaded()" ...
    

    我刚才有一种情况,我还需要在提交表单提交后从 IFRAME 本身调用 iframeLoaded . 您可以通过在 IFRAME 的内容脚本中执行以下操作来实现此目的:

    parent.iframeLoaded();
    
  • 0

    我找到的最简单的方法是使用javscript / jquery,而不是使用javscript / jquery:

    <iframe style="min-height:98vh" src="http://yourdomain.com" width="100%"></iframe>
    

    这里1vh =浏览器窗口高度的1% . 因此,要设定的高度的理论值是100vh,但实际上98vh是神奇的 .

  • 0

    您还可以在resizeIframe中添加重复的requestAnimationFrame(例如来自@ BlueFish的答案),在浏览器绘制布局之前总是会调用它,并且当内容更改其高度时,您可以更新iframe的高度 . 例如输入表格,延迟加载内容等

    <script type="text/javascript">
      function resizeIframe(iframe) {
        iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
        window.requestAnimationFrame(() => resizeIframe(iframe));
      }
    </script>  
    
    <iframe onload="resizeIframe(this)" ...
    

    你的回调应该足够快,不会对你的整体表现产生太大影响

  • 48

    简单的解决方案是测量内容区域的宽度和高度,然后使用这些测量值来计算底部填充百分比 .

    在这种情况下,测量值为1680 x 720 px,因此底部的填充为720/1680 = 0.43 * 100,达到43% .

    .canvas-container {    
        position: relative;
        padding-bottom: 43%; // (720 ÷ 1680 = 0.4286 = 43%)
        height: 0;
        overflow: hidden;   
    }
    
    .canvas-container iframe {    
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;   
    }
    
  • 0

    您可以通过四种不同的属性来获取iFrame中内容的高度 .

    document.documentElement.scrollHeight
    document.documentElement.offsetHeight
    document.body.scrollHeight
    document.body.offsetHeight
    

    可悲的是,他们都可以给出不同的答案,这些在浏览器之间是不一致的 . 如果将body margin设置为0,那么 document.body.offsetHeight 会给出最佳答案 . 要获得正确的值,请尝试此功能;这是从 iframe-resizer 库中获取的,该库也会在内容更改或调整浏览器大小时保持iFrame的正确大小 .

    function getIFrameHeight(){
        function getComputedBodyStyle(prop) {
            function getPixelValue(value) {
                var PIXEL = /^\d+(px)?$/i;
    
                if (PIXEL.test(value)) {
                    return parseInt(value,base);
                }
    
                var 
                    style = el.style.left,
                    runtimeStyle = el.runtimeStyle.left;
    
                el.runtimeStyle.left = el.currentStyle.left;
                el.style.left = value || 0;
                value = el.style.pixelLeft;
                el.style.left = style;
                el.runtimeStyle.left = runtimeStyle;
    
                return value;
            }
    
            var 
                el = document.body,
                retVal = 0;
    
            if (document.defaultView && document.defaultView.getComputedStyle) {
                retVal =  document.defaultView.getComputedStyle(el, null)[prop];
            } else {//IE8 & below
                retVal =  getPixelValue(el.currentStyle[prop]);
            } 
    
            return parseInt(retVal,10);
        }
    
        return document.body.offsetHeight +
            getComputedBodyStyle('marginTop') +
            getComputedBodyStyle('marginBottom');
    }
    
  • 3
    $(document).height() // - $('body').offset().top
    

    和/或

    $(window).height()
    

    请参阅Stack Overflow问题How to get the height of a body element .

    试试这个在jQuery中找到body的高度:

    if $("body").height()
    

    如果Firebug,它没有值 . 也许这就是问题所在 .

  • 0

    将此添加到iframe,这对我有用:

    onload="this.height=this.contentWindow.document.body.scrollHeight;"
    

    如果您使用jQuery尝试此代码:

    onload="$(this).height($(this.contentWindow.document.body).find(\'div\').first().height());"
    
  • 0

    我发现特洛伊的答案没有用 . 这是为ajax重做的代码:

    $.ajax({                                      
        url: 'data.php',    
        dataType: 'json',                             
    
        success: function(data)
        {
            // Put the data onto the page
    
            // Resize the iframe
            var iframe = $(window.top.document).find("#iframe");
            iframe.height( iframe[0].contentDocument.body.scrollHeight+'px' );
        }
    });
    
  • 2

    我发现接受的答案是不够的,因为X-FRAME-OPTIONS:Allow-From isn't supported in safari or chrome . 采用了不同的方法,发现于来自Disqus的Ben Vinegar给出的presentation . 想法是向父窗口添加一个事件监听器,然后在iframe内部使用window.postMessage发送一个事件给父母告诉它做某事(调整iframe的大小) .

    所以在父文档中,添加一个事件监听器:

    window.addEventListener('message', function(e) {
      var $iframe = jQuery("#myIframe");
      var eventName = e.data[0];
      var data = e.data[1];
      switch(eventName) {
        case 'setHeight':
          $iframe.height(data);
          break;
      }
    }, false);
    

    在iframe中,编写一个函数来发布消息:

    function resize() {
      var height = document.getElementsByTagName("html")[0].scrollHeight;
      window.parent.postMessage(["setHeight", height], "*"); 
    }
    

    最后,在iframe内部,向body标签添加onLoad以触发resize函数:

    <body onLoad="resize();">
    

相关问题