【问题标题】:It is possible to Resize an iframe without reloading the frame?可以在不重新加载框架的情况下调整 iframe 的大小吗?
【发布时间】:2015-01-12 11:40:53
【问题描述】:

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

规则:

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

Window 和 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?");
                });
            }
        }
    }

【问题讨论】:

    标签: javascript jquery html iframe


    【解决方案1】:

    试试这个,

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

    【讨论】:

    • 你写的我已经在我的代码中了。问题是,无论如何我都需要触发器或重新加载。无论如何谢谢 :) 编辑:我在代码中完成的触发器由于某种原因无法正常工作。我会尽可能动态地做到这一点,我会与你分享。
    • 好的。但是你应该把你的代码放在问题中,这样我们就可以更容易地看到问题;)
    • 我的朋友。我有很多未定义的测试条件,因为这段代码在我的项目中是全局的。您的解决方案与我的几乎相同,但使用框架选择器作为函数中的参数似乎更好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多