码迷,mamicode.com
首页 > 其他好文 > 详细

坑爹的跨域iframe高度

时间:2015-04-13 18:40:41      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

如果遇到子页面跨域的问题,可通过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> 

<iframe src=‘abc.html‘ id="frm1" onload="resizeCrossDomainIframe(‘frm1‘, ‘http://example.com‘);">

 

同域下的高度自适应

<iframe src="http://demo.cn/downloadapp/demo.html" frameborder="0" width="100%" style="opacity:1" height=100% id="iframepage" name="iframepage" onLoad="iFrameHeight()">
</iframe>

<script>
    function iFrameHeight() {

        var ifm= document.getElementById("iframepage");
        var subWeb = document.frames ? document.frames["iframepage"].document : ifm.contentDocument;

        if(ifm != null && subWeb != null) {
            ifm.height = subWeb.body.scrollHeight;
        }
    }
</script>

 

坑爹的跨域iframe高度

标签:

原文地址:http://www.cnblogs.com/oceanden/p/4422704.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!