Iframe跨域嵌入页面自动调整高度的办法

http://www.a.com/A.html

http://www.a.com/B.html

http://www.a.com/D.js  

http://www.c.com/C.html

 

A.html:

<iframe id="iframe_shg" src="http://www.c.com/c.html" frameborder="0" width="100%"></iframe>

________________________________________________________________

B.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title>B.html</title>
</head>
<body>
    <script type="text/javascript">
        window.onload = function() {
            var isSet = false
            var inteval = setInterval(function() {
                var search = location.search.replace('?', '')
                if (isSet) {
                    clearInterval(inteval)
                    return
                }
                if (search) {
                    var height = search.split('=')[1]
                    var doc = parent.parent.document
                    var ifr = doc.getElementById('iframe_shg')
                    ifr.style.height = height + 'px'
                    isSet = true
                }
            }, 500)
        }
    </script>
</body>
</html>

________________________________________________________________

D.js

// 计算页面的实际高度,iframe自适应会用到
function calcPageHeight(doc) {
    var cHeight = Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
    var sHeight = Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight)
    var height = Math.max(cHeight, sHeight)
    return height
}
window.onload = function () {
    var doc = document
    var height = calcPageHeight(doc)
    var myifr = doc.getElementById('myifr')
    if (myifr) {
        myifr.src = 'http://www.a.com/B.html?height=' + height
        // console.log(doc.documentElement.scrollHeight)    
    }
};

_________________________________________________________________

C.html

<body>

........................

    <iframe id="myifr" style="display:none" src="http://www.a.com/B.html"></iframe>
    <script type="text/javascript" src="http://www.a.com/D.js"></script>

</body>

 

posted @ 2016-01-07 22:57  sekon  阅读(525)  评论(0编辑  收藏  举报