如果遇到子页面跨域的问题,可通过HTML5的postMessage来实现,但前提是子页面需要主动向父页面发送信息。下面是子页面部分: 复制代码 代码如下: <!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>