使用 jQuery Event 调整内容窗口高度

Adjust contentWindow height with jQuery Event

本文关键字:窗口 高度 调整 jQuery Event 使用      更新时间:2023-09-26

这是我到目前为止所拥有的,使用这篇文章:

让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');
    });
}

这是我的网页

<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";

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

我遇到了这个问题。这是我能够使其工作的方法。

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()并且它起作用了。

我能够使用此框架来获得我想要的解决方案。

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>

哪个奏效了!