跨域 iframe 调整器? [英] cross-domain iframe resizer?

查看:26
本文介绍了跨域 iframe 调整器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个很好的跨域 iframe 大小调整脚本,该脚本根据其内容调整其高度.我也可以访问 iframe 源的 html/css.有吗?

I'm looking for a good cross-domain iframe resizing script that adjusts its height based on its content. I have access to the html/css for the source of the iframe as well. Is there any out there?

推荐答案

如果您的用户使用现代浏览器,您可以使用 HTML5 中的 postMessage.这是一个运行良好的快速解决方案:

If your users are on modern browsers, you can solve this quite easily with postMessage in HTML5. Here's a quick solution which works well:

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 的父页面(并想知道其高度):

The parent page which contains the iframe (and would like to know its height):

<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>

这篇关于跨域 iframe 调整器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆