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

标签 javascript jquery html iframe

您好 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?");
                });
            }
        }
    }

最佳答案

试试这个,

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

$('iframe').load(function(){
    resizeIframe(this);
});

关于javascript - 可以在不重新加载框架的情况下调整 iframe 的大小吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27901136/

相关文章:

javascript - 当两个条件不满足时禁用发送按钮在 ember.js 中不起作用

javascript - 下载 JPG、PNG 格式时,签名板上的 Canvas 签名变成全黑

css - 如何使 float <div> 使用其最大宽度

Javascript reduce - 在多个变量中拆分累加器

javascript - 使用客户端 Javascript 从 Node 的 readStream 保存图像

javascript - ui-router 动态创建嵌套状态

javascript - jquery 检查元素是否存在,数据属性只匹配特定值的开头

javascript - 有没有办法在不同的滚动点改变不同的图像?

javascript - 使用 JS 突出显示 &lt;textarea&gt; 中的特定部分

javascript - React 15 - 查找元素的 offsetTop 属性