如何设置iframe高度自适应,在跨域的状况下能作到吗?

  在页面上使用iframe来动态加载页面内容是网页开发中比较常见的方法。在父页面中给定一个不带滚动条的iframe,而后对属性src指定一个可加载的页面,这样当父页面被访问的时候,子页面能够被自动加载。iframe的高度须要根据子页面的实际高度来进行调整。若是iframe的高度小于子页面的实际高度,超出的部分没法显示;相反,若是iframe的高度太高,则页面上会出现大量的空白区域。咱们能够经过属性或者CSS来设置iframe的高度,当不肯定子页面内容的高度时,也能够经过脚原本进行动态指定。可是若是子页面不在同一域中怎么办?这时候脚本没有办法获取到子页面的高度,存在JavaScript跨域的问题!javascript

  如题所述,本文在介绍可用方法的同时,也向你们询问除下文列出来的方法以外是否还有其它方法可寻?html

  经过属性或CSS来设置iframe的高度这里就再也不具体介绍了。首先来看看如何经过脚本进行设置。html5

function ChangeFrameHeight(id) {
    var count = 1;
    
    (function() {
    var frm = document.getElementById(id);
    var subWeb = document.frames ? document.frames[id].document : frm.contentDocument;

        if (subWeb != null) {
            var height = Math.max(subWeb.body.scrollHeight, subWeb.documentElement.scrollHeight);
            frm.height = height;
        }
        if (count < 3) {
            count = count + 1;
            window.setTimeout(arguments.callee, 2000);
        }
    })();
}

  假设iframe子页面和父页面都在同一域内,经过该脚本能够对给定id的iframe高度进行动态调整。为了防止父页面在子页面以前加载完成,该函数会每隔2秒从新执行一次,一共执行3次。极端状况下子页面的加载速度会慢于父页面,可适当对执行次数和时间作调整。java

<iframe frameborder="0" width="450"  marginheight="0" marginwidth="0" scrolling="no" id="frm1" name="frm1" src="abc.html" onload="ChangeFrameHeight('frm1')"></iframe>

   若是遇到子页面跨域的问题,可经过HTML5的postMessage来实现,但前提是子页面须要主动向父页面发送信息。下面是子页面部分:web

<!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='abc.html' id="frm1" onload="resizeCrossDomainIframe('frm1', 'http://example.com');">
</iframe>

  有关如何使用HTML5的postMessage()方法能够查看这篇文章http://dev.w3.org/html5/postmsg/#web-messagingdom

  可是在大多数状况下,iframe中所引用的子页面除了和父页面不在同一域以外,咱们可能根本没法对子页面进行任何操做,或者说子页面根本没有提供Corss-document messaging功能。在这种状况下,经过postMessage()方法也没法获取到子页面的任何信息。因为没法和子页面进行任何交互,也就没有办法得知子页面的document对象,从未没法根据子页面的实际高度来调整父页面iframe的height属性了。ide

  目前没有其它实际有效的方法来处理上面遇到的问题。默认状况下能够给iframe指定一个比较大的高度,这样假设所引用的子页面内容不会超出范围,除了在页面上会留下部分空白区域外,内容显示基本不会有问题。函数

  那是否还存在其它比较有效的解决方法呢?期待!post

相关文章
相关标签/搜索