欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iframe自适应高度问题

程序员文章站 2022-07-14 21:54:23
...

1、不跨域
iframe的页面直接修改包裹着它的iframe的高度就行
2、跨域
用postMessage
https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage

下面是demo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <iframe src="http://127.0.0.1:4321/b.html" frameborder="0" width="100%" id="iframe-b"></iframe>

    <script type="text/javascript">
        window.onload = function() {
            window.addEventListener('message', function(event) {
            if (event.origin === "http://127.0.0.1:4321") {
                document.getElementById("iframe-b").style.height = event.data + "px";
                console.log(event.data)
            }
            }, false);
        }
    </script>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<style>
    .hello {
        width: 200px;
        height: 500px;
        background-color: red;
    }
</style>
<body>
    <div class="hello">

    </div>
    <script type="text/javascript">
        // window.onload = function() {
        //     var h  = document.body.scrollHeight;
        //     parent.postMessage(h, "http://127.0.0.1:1234");
        // }
        setTimeout(() => {
            var h  = document.body.scrollHeight;
            parent.postMessage(h, "http://127.0.0.1:1234");
        }, 500);
    </script>
</body>
</html>