iframe自适应高度处理方案

第一种:这个方案能解决大多数自适应高度问题,方法是在iframe所要加载的页面上添加代码,把它的高度告诉iframe所在页面。缺点显而易见,如果iframe要加载的页面非常多而且不固定那么代码加起来很麻烦。

$(function () {
    fixParentHeight();
});

function fixParentHeight() {
    var thisbodyheight = document.body.clientHeight;
    $(window.parent.document).find("#iframe").height(thisbodyheight);
}

第二种:获取iframe与浏览器顶部的距离,用浏览器全高减去这个距离,得到iframe到底部的距离,将这个作为iframe高度。缺点是这个高度不能跟随iframe动态调整,如果iframe高度很小那么它还是会占据屏幕整个下半部分。

    function stretchHeight(targetobj, delta) {
        var sf = function () {
            var tableWrap = $(targetobj);
            var tableOffset = tableWrap.offset();
            var documentHeight = $(document.documentElement).height();
            if ($.browser.msie) {
                documentHeight = document.documentElement.clientHeight;
            } else {
                documentHeight = window.innerHeight;
            }
            var tableHeight = documentHeight - tableOffset.top - (delta == undefined ? 0 : delta);
            tableWrap.height(tableHeight);
        };
        sf();
        $(window).resize(function () {
            sf();
        });
    }
    stretchHeight($("#iframe"), 10);
原文地址:https://www.cnblogs.com/duelsol/p/4717260.html