js控制iframe高度兼容ie浏览器

需求:

  在一个列表页面中需要在点开的时候展开列表信息对应的详细信息页,由于信息展示用到的是静态页面,所以首先想到的是ifram加载详细信息页;

由此引发了iframe加载页面后高度没有适应详细信息页内容的高度的问题。

以下代码为参考网上其他博客做出:

//展开点击事件
    $('.ewb-public-main').on('click', '.ewb-public-node', function(event) {
        var $this = $(this).parent();
        if (event.target.className != 'ewb-public-arrow') {
            $(".ewb-public-link").each(function(index, element) {
                if (!$(this).is($this)) {
                    $(this).removeClass('active');
                }
                $(".ewb-public-link").find(".ewb-public-arrow").text("展开");
            });
            $this.toggleClass('active');
            $(".ewb-public-link.active").find(".ewb-public-arrow").text("收起");
            var iframeid = $this.find(".ewb-public-block").find("iframe").attr("id");
            //alert(iframeid);
            dyniframesize(iframeid);
        }
    });
    
    //iframe页面宽度、高度自适应, down为iframe的id
    function dyniframesize(down) {
        var pTar = null;
        if (document.getElementById) {
            pTar = document.getElementById(down);
        } else {
            eval('pTar = ' + down + ';');
        }
        if (pTar && !window.opera) {
            //begin resizing iframe 
            pTar.style.display = "block"
            if (pTar.contentDocument && pTar.contentDocument.body.offsetHeight) {
                //ns6 syntax 
                //alert(pTar.contentDocument.body.offsetHeight);
                pTar.height = pTar.contentDocument.body.offsetHeight + 60;
                pTar.width = pTar.contentDocument.body.scrollWidth + 60;
            } else if (pTar.Document && pTar.Document.body.scrollHeight) {
                //ie5+ syntax 
                //alert(pTar.Document.body.scrollHeight);
                pTar.height = pTar.Document.body.scrollHeight;
                pTar.width = pTar.Document.body.scrollWidth;
            }
        }
    }

以上代码兼容ie9以上,尤其360安全浏览器。

初心回归,时光已逝!
原文地址:https://www.cnblogs.com/yin1361866686/p/9835281.html