【问题标题】:How to resize the iframe in cross domain url如何在跨域 url 中调整 iframe 的大小
【发布时间】:2016-05-04 06:11:06
【问题描述】:

任何人都可以告诉我正在尝试在 iframe onload 函数中加载 url。我想在没有滚动条的情况下显示 iframe 并调整其内容,但父页面将根据内容滚动任何人都可以告诉我如何调整 iframe 的大小跨域网址?

谢谢

【问题讨论】:

    标签: javascript angularjs iframe


    【解决方案1】:

    为了根据内容调整 iframe 的大小,您不能使用 postMessage 将当前 iframe 高度发送给其父级。

    包含在 iFrame 中的页面需要使用 postMessage 将其当前高度发送到包含页面。 包含页面必须监听该消息并相应地更改 iframe 的高度。

    包含页面中的代码可能如下所示:

    function getBottom() {
        var max = jQuery("body").height();
        //Your additional calculations go here
        return max;
    }
    
    function updateHeight() {
        sendHeightToParent();
        setTimeout(updateHeight, 500);
    }
    
    function sendHeightToParent() {
        var messageObject = {
            "type":"size",
            "version":"1.0.0",
            "params":{
                "height": getBottom()
            }
        };
    
        //YOURTARGET is the target page if known. Otherwise use "*"
        parent.postMessage(JSON.stringify(messageObject), "YOURTARGET");
    }
    
    //Only possible if html5 post message is available
    if (typeof parent.postMessage == 'function') {
        jQuery().ready(function() {
            sendHeightToParent();
            setTimeout(updateHeight, 500);
        });
    }
    

    然后父级监听事件并相应地更新 iframe:

    //Only possible if html5 post message is available
    if (typeof parent.postMessage == 'function') {
        window.addEventListener("message", function (e) {
            obj = JSON.parse(e.data);
            if (obj.type == 'size') {
                myFrame = document.getElementById('YouIFrameId');
                myFrame.stye.height = obj.params.height + "px";
            }
        }
    }
    

    【讨论】:

    • 从body标签我需要调用哪个方法或者需要从iframe调用。你能更新代码吗
    • 在包含 iframe 的页面中添加第二个代码。在包含的页面中添加第一个代码。
    • 。我在 index.jsp 的同一页面中添加了 iframe
    猜你喜欢
    • 2011-08-20
    • 2011-08-02
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 2014-08-30
    相关资源
    最近更新 更多