Iframe的高度自适应且兼容谷歌,火狐,IE和360等主流浏览器

来源:互联网 发布:淘宝进销存系统 编辑:程序博客网 时间:2024/05/16 15:13

子页面不用任何操作,只要在主页面进行这些操作就可以完成iframe的高度自适应

1,需要知道iframe的ID

<iframe id="mainFrame" name="mainFrame" scrolling="no" src="Index.aspx" frameborder="0" style="padding: 0px; width: 100%; height: 1000px;"></iframe>


2,调用时 需要传入两个值,iframe的Id和iframe最小高度

只有一个iframe需要调用可以这样

setHeightAuto('mainFrame', 560);

当多个iframe时并且都没有设置Id的情况下可用for循环来实现所有的iframe都调用

for(var i=0;i<=$('.content iframe').length;i++){

$($('.content iframe')[i]).attr('id','iframe'+i);

setHeightAuto('iframe'+i,600);

}


3,引入autoHeight.j文件文件内容是

var browserVersion = window.navigator.userAgent.toUpperCase();
var isOpera = browserVersion.indexOf("OPERA") > -1 ? true : false;
var isFireFox = browserVersion.indexOf("FIREFOX") > -1 ? true : false;
var isChrome = browserVersion.indexOf("CHROME") > -1 ? true : false;
var isSafari = browserVersion.indexOf("SAFARI") > -1 ? true : false;
var isIE = (!!window.ActiveXObject || "ActiveXObject" in window);
var isIE9More = (! -[1, ] == false);
function reinitIframe(iframeId, minHeight) {
    try {
        var iframe = document.getElementById(iframeId);
        var bHeight = 0;
        if (isChrome == false && isSafari == false){
            bHeight = iframe.contentWindow.document.body.scrollHeight;
}

        var dHeight = 0;
        if (isFireFox == true)
            dHeight = iframe.contentWindow.document.documentElement.offsetHeight + 2;
        else if (isIE == false && isOpera == false)
            dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
        else if (isIE == true && isIE9More) {//ie9+
            var heightDeviation = bHeight - eval("window.IE9MoreRealHeight" + iframeId);
            if (heightDeviation == 0) {
                bHeight += 3;
            } else if (heightDeviation != 3) {
                eval("window.IE9MoreRealHeight" + iframeId + "=" + bHeight);
                bHeight += 3;
            }
        }
        else//ie[6-8]、OPERA
            bHeight += 3;
        var height = Math.max(bHeight, dHeight);
        if (height < minHeight) height = minHeight;
        iframe.style.height = height + "px";
    } catch (ex) { }
}
function setHeightAuto(iframeId, minHeight) {

    eval("window.IE9MoreRealHeight" + iframeId + "=0");

//这里添加个定时器是因为当iframe由于某些操作高度发生变化时,能够随时调整。

    window.setInterval("reinitIframe('" + iframeId + "'," + minHeight + ")", 100);
}

本文也是借鉴网友的http://www.cnblogs.com/slyzly/articles/2422737.html

 

1 0