1

我正在尝试使用easyXDM根据其内容高度动态调整iframe的高度。该代码每 5 秒调用一次检查 iframe 的 body.scrollheight,理论上如果页面高度发生了变化,则 iframe 高度将每 5 秒更新一次。它适用于初始调用 - iframe 甚至可以正确调整大小。问题在于,即使 iframe 内容的高度发生了变化,提供程序也会继续返回内容的原始高度。

编码:

消费者(包含 iframe 的页面):

var socket = new easyXDM.Socket({
remote: "http://remoteDomain.ca/blahblah.html",
container: "embedded",
onMessage: function(message, origin){
    alert(message); //continually alerts "542px" even when body.scrollheight 
                    // has changed
   document.getElementById('iframe').style.height = message + "px";  
   var t = setTimeout(function() {
      socket.postMessage();
   }, 5000);
},
onReady: function() {
    socket.postMessage();
}
});

提供者(iframe 内容):

var socket = new easyXDM.Socket({
    onMessage: function(message, origin){
        socket.postMessage(document.body.scrollHeight);
    }
});
4

1 回答 1

1

After try easyXDM, it finally worked by using another sample: http://stevesouders.com/misc/test-postmessage.php

In source page just:

<script type="text/javascript">
    setInterval(function () {
        parent.postMessage(document.body.scrollHeight, '*');
    }, 500);    
</script>

In frame page:

<script type="text/javascript">

    if (window.attachEvent) {
        // IE
        window.attachEvent("onmessage", handleMessage);
    }

    if (window.addEventListener) {
        // FF
        window.addEventListener("message", handleMessage, false);
    }

    function handleMessage(e) {
        $("#frameId").attr("height", e.data);
    }

</script>
<iframe id="frameId" src="http://mysourceurl.com.br/" width="100%"
    frameborder="0" scrolling="no"></iframe>

Worked like a charm! My iframe height is refreshed every setInterval interation.

于 2012-06-06T15:00:33.373 回答