使用jQuery事件调整contentWindow高度

3
这是我目前使用此文章的代码:
使用此帖子:如何使iframe根据内容自动调整高度而不使用滚动条? 问题在于函数resizeIframe()似乎在再次调用后不会改变任何东西。框架大小不会改变。
这是我的完整代码:
function resizeIframe(obj) {
    obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}

$(document).ready(function() {

// change iframe based on drop down menu //

    $('#dropdown').click(function(){
        $('iframe').slideUp("slow");
        $('iframe').attr('src', 'preview.php?frame=off&sid='+$(this).val());
        resizeIframe(document.getElementById('previewframe'));
        $('iframe').slideDown('slow');
    });
}

这是我的HTML。
<iframe id="previewframe" src="preview.php?frame=off&sid=1" style="width: 100%; overflow-x: hidden; overflow-y: scroll" onload='javascript:resizeIframe(this);'>
</iframe>

回答前请阅读此编辑

编辑:我已经离成功近了几步,但还没有达到目标。

所以在 iframe 源 HTML 中,我在 body 底部嵌入了以下内容:

<script type="text/javascript">
    parent.AdjustIframeHeight(parseInt(document.getElementById("body").scrollHeight));
</script>

然后我在我的主文件中有以下内容:
<iframe name="previewframe" id="previewframe" src="preview.php?frame=off&sid=1" style="width: 100%; overflow-x: hidden; overflow-y: scroll;">
</iframe>
<script type="text/javascript">
    function AdjustIframeHeight(i) {
        alert("CHANGING: " + parseInt(i));
        document.getElementById('previewframe').style.height = parseInt(i) + "px";
        alert("Current value: " + document.getElementById('previewframe').style.height);
    }
</script>

一切运作良好,正确的值被发送到警报中,第二个警报发送回最初传递的值,但实际的框架高度并没有改变。

真正奇怪的是,如果我打开控制台,并手动输入:

document.getElementById('previewframe').style.height = "800px";

它将完美地工作。因此,这让我相信浏览器只需要以某种方式更新设置的高度。

2个回答

2
我遇到了这个问题。以下是我如何解决它的方法。
myiframe.css('visibility', 'hidden' );
myiframe.css('height', '1px' );
myiframe.css('height', myiframe.contents().height() ); // get the size of the iframe content height.
myiframe.css('visibility', 'visible' );

我得到了隐藏并使其可见的想法来自于这个链接,但仅靠这个还不够。我从document.getElementById(id).style.height改为了myiframe.css(),然后它就有效了。


1
我能使用这个框架得到我想要的解决方案。

https://github.com/davidjbradshaw/iframe-resizer

我的主文件有这段代码:
<iframe id="previewframe" src="preview.php?frame=on&sid=1" style="width: 100%; overflow-x: hidden; overflow-y: scroll;"></iframe>

<script type="text/javascript">
    $('iframe').iFrameResize({
        log                     : false,   // Enable console logging
        enablePublicMethods     : true,    // Enable methods within iframe hosted page
        resizedCallback: function (obj) {
            $('iframe').slideUp("slow");
            $('iframe').slideDown("slow");
        }
    });
</script>

我的框架有这段代码。
     <script type="text/javascript" src="js/iframeResizer.contentWindow.min.js"></script>
     <script>
        var please = function(){
          if ('parentIFrame' in window){
            parentIFrame.setHeightCalculationMethod('max'); 
          }
        };
    </script>
</body>

哪个起作用了!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接