可以在不重新加载框架的情况下调整 iframe 的大小

It is possible to Resize an iframe without reloading the frame?

本文关键字:情况下 框架 调整 iframe 加载 新加载      更新时间:2023-09-26

嗨堆栈溢出社区。我有一个问题。我有一个使用iFrame的过程。这个过程有一些Javascript来根据iFrame内容设置iFrame高度。我认为这还不够,所以我决定根据内容更改自动调整 iFrame 高度的大小,而无需重新加载任何 iFrame 或进程。不幸的是,我尝试过,但由于怀疑而无法做到。我在堆栈溢出中到处搜索,但没有找到解决方案。

规则:

  • 在 iFrame 中自动调整高度大小。
  • 不会在父窗口或 iFrame 中重新加载。
  • 没有
  • 触发器,没有间隔。
  • 一切都是自动的。

窗口和 iFrame 位于同一域中。

你能帮帮我吗?谢谢,很抱歉英语不好。

我的实际代码:

if(document.getElementById("frame") != undefined)
{
    var frame = document.getElementById("frame");
        $(frame).load(function(){
            var frame_height = frame.contentWindow.document.body.scrollHeight + 'px';
            frame.setAttribute('style', 'height:' + frame_height + ' !important');
            console.log('its this loading?');
            contentBasedIframeResize(); //this is worthless, just testing. isn't dynamic right now. need fix.
        // As soon as the frame finish the load, this frame height will be based in the frame content
        });
        function contentBasedIframeResize()
        {
            var add_button = $(frame).contents().find(".some_obj"); //preparing the trigger
            var remove_button = $(frame).contents().find(".some_obj"); //preparing the trigger
            if(add_button != undefined)
            {
                $(add_button).click(function(){
                    var add_height = frame.contentWindow.document.body.scrollHeight + 'px';
                    frame.setAttribute('style', 'height:' + add_height + ' !important');
                });
            }
            if(remove_button != undefined)
            {
                $(remove_button).click(function(){
                    var remove_height = $("#frame").contents().find("#table_obj").height();
                    remove_height = parseInt(remove_height) + 100; //hardcoded
                    frame.setAttribute('style', 'height:' + remove_height + 'px !important');
                    console.log("its this working v2?");
                });
            }
        }
    }

试试这个,

function resizeIframe(obj)
{
    obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
$('iframe').load(function(){
    resizeIframe(this);
});