使用chrome自动调整iframe大小

时间:2012-11-05 02:59:06

标签: javascript jquery html5

我被要求根据内容重新调整iframe的大小。经过长时间的搜索,我终于让它按需要工作,但它只适用于Firefox。我需要它至少在chrome,ff和ie上工作。这是脚本

<script language="JavaScript">
<!--
function autoResize(id){
    var newheight;

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document.body.scrollHeight; //ff
        newheight=document.getElementById(id).contentDocument.body.offsetHeight; //chrome
        newheight=document.getElementById(id).contentDocument.documentElement.scrollHeight;

        }

    document.getElementById(id).height= (newheight) + "px";
}
//-->
</script>

和iframe代码

<iframe name="result" id="iframe" seamless src="action/search.php" width="100%" onLoad="autoResize('iframe');" marginwidth=0 marginheight=0 frameborder=0 scrolling="no" style="border:0; overflow:hidden">
    </iframe>

任何建议都表示赞赏。

2 个答案:

答案 0 :(得分:0)

试试这个

onload="if (window.parent &amp;&amp; window.parent.autoIframe) {window.parent.autoIframe('tree');}
iframe中的

<script type="text/javascript">
    function autoIframe(frameId){
        try{
            frame = document.getElementById(frameId);
            innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;

            if (innerDoc == null){
                            // Google Chrome
                frame.height = document.all[frameId].clientHeight + document.all[frameId].offsetHeight + document.all[frameId].offsetTop;
            }
                    else{
                    objToResize = (frame.style) ? frame.style : frame;
                    objToResize.height = innerDoc.body.scrollHeight + 18;
                    }
        }

        catch(err){
                alert('Err: ' + err.message);
            window.status = err.message;
        }
    }
    </script>

答案 1 :(得分:0)

不应直接在元素上设置高度,而应将其设置为属性:

var heightAttr = document.createAttribute("height");
heightAttr.value = newheight;
document.getElementById(id).attributes.setNamedItem(heightAttr);

或者您可以在css对象中设置它:

document.getElementById(id).style.height = (newheight) + "px";
相关问题