How to auto shrink iframe height dynamically?

后端 未结 3 1616
慢半拍i
慢半拍i 2020-12-17 06:09

I use the following code to achieve dynamic iframe height:

In the :



        
3条回答
  •  攒了一身酷
    2020-12-17 06:25

    I thought about it quite a bit, and think I came up with another solution that may resolve your problem from the parent document. Rather than editing the documents in your iframe. However I can't test it due to cross origin policy. Try this out and let me know how it works.

    var iframeDoc = $('iframe[name="dservers"]').contents().get(0);
    $('iframe[name="dservers"]').load(function(){
        docHeight = $(iframeDoc).height();
        $('iframe[name="dservers"]').height( docHeight );
    });
    

    Hope this does it for you.

    Edit: This fix would require you to remove the onload="" function.

    Edit-2: You seem to have combined the two scripts. You have this:

      function resizeIframe(obj) {
        obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
        var iframeDoc = $('iframe[name="dservers"]').contents().get(0);
    $('iframe[name="dservers"]').load(function(){
        docHeight = $(iframeDoc).height();
        $('iframe[name="dservers"]').height( docHeight );
    });
      }
    

    Replace that entire script with this:

    $(function(){
        var iframeDoc = $('iframe[name="dservers"]').contents().get(0);
        $('iframe[name="dservers"]').load(function(){
            docHeight = $(iframeDoc).height();
            $('iframe[name="dservers"]').height( docHeight );
        });
    });
    

    And remove the onload="resizeFrame()" from the iframes tag.

提交回复
热议问题