1

我有一个跨域 iFrame。实际的 iFrame 工作正常,并以 100% 的高度显示页面。

我的问题是第一页大约 1200 像素高,然后如果您单击 iframe 中的链接并且下一页是 800 像素,您会在底部获得 400 像素的空白区域。

所以 iframe 会变大以适应内容,但不会缩小。下面是我的代码:

进入要进行 iframe 的页面中的代码:

<!DOCTYPE html>
<head>
</head>
<body onload="parent.postMessage(document.body.scrollHeight, 'http://target.domain.com');">
  <h3>Got post?</h3>
  <p>Lots of stuff here which will be inside the iframe.</p>
</body>
</html>

进入接收 iframe 的页面的代码:

<script type="text/javascript">
  function resizeCrossDomainIframe(id, other_domain) {
    var iframe = document.getElementById(id);
    window.addEventListener('message', function(event) {
      if (event.origin !== other_domain) return; // only accept messages from the specified domain
      if (isNaN(event.data)) return; // only accept something which can be parsed as a number
      var height = parseInt(event.data) + 32; // add some extra height to avoid scrollbar
      iframe.height = height + "px";
    }, false);
  }
</script>

<iframe src='http://example.com/page_containing_iframe.html' id="my_iframe"    onload="resizeCrossDomainIframe('my_iframe', 'http://example.com');">
</iframe>

有谁知道如何修改javascript使其也缩小?

谢谢你。

4

1 回答 1

1

在您的脚本中 other_domain 等于 'http://example.com' - 总是。因此,如果您单击“http://example.com/somePage.html”,您的函数将始终在调整 iFrame 大小之前返回。而不是等于,你应该使用

if (event.origin.lastIndexOf(other_domain, 0) !== 0) return;
于 2012-11-01T19:31:12.343 回答