iframe同域自适应问题

同域的我们可以轻松的做到

1. 父页面通过iframe的contentDocument或document属性访问到文档对象,进而可以取得页面的高度,通过此高度值赋值给iframe tag。

2. 子页面可以通过parent访问到父页面里引入的iframe tag,进而设置其高度。

Html1.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>1.html</title>
   
</head>
<body>
//这句很重要
       <iframe id="ifr" src="Html2.html" frameborder="0" width="100%"></iframe>
</body>
</html>

Html2.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>2.html</title>
  
</head>
<body>
    <p>这是一个ifrmae,嵌入在Html1.html里!!!! </p>
    <p>根据自身内容调整高度</p>
    <p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p>
    <script>
        // 计算页面的实际高度,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 height = calcPageHeight(document)
            parent.document.getElementById('ifr').style.height = height + 'px'
        }
    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/weiyu11/p/7158884.html