怎样解决iframe高度自适应问题

2021年5月6日 | 分类: 【技术】

参考:https://segmentfault.com/a/1190000014586956

主页面:a.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>a</title>
</head>

<body style="background-color:red">
    <iframe id="iFrame" class="flexiframe" src="./b.html" style="padding: 0;width:100%;" marginwidth="0" frameborder="no" scrolling="no" height="2000px"></iframe>
    <!-- <iframe id="iFrame1" class="flexiframe" src="./b.html" style="padding: 0;width:100%" marginwidth="0" frameborder="no" scrolling="no"></iframe> -->
    <!-- <iframe id="iFrame2" class="flexiframe" src="./b.html" style="padding: 0;width:100%" marginwidth="0" frameborder="no" scrolling="no"></iframe> -->
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <script src="./flexiframe.js"></script>
</body>

</html>

./flexiframe.js

// 使用前先将子页面文档声明改为
//<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
function setIframeHeight(iframe) {
    if (iframe) {
        var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;
        if (iframeWin.document.body) {
            iframe.height = iframeWin.document.body.scrollHeight;
        }
    }
};
$(".flexiframe").each(function (index) {
    var that = $(this);
    (function () {
        setInterval(function () {
            setIframeHeight(that[0])
        }, 200)
    })(that)
});

子页面:b.html

分别注释两种声明方式,点击变大变小按钮看一下右侧滚动条的变化,(细节可以F12看一下iframe种的html和body跟div的高度关系)

<!-- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -->
<!DOCTYPE html>
<div id="b_conntent">
        <div style="width:100px;background-color:blue">
                <div style="height:2000px">
                        <button id="btn">小</button>
                </div>
        </div>
</div>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
        $('#btn').on('click', function () {
                if ($(this).text() == '小') {
                        $(this).text('大').parent().css('height', '200px')
                } else {
                        $(this).text('小').parent().css('height', '2000px')
                }
        })
</script>