用于增加在Google Chrome中无效的iframe高度的代码

时间:2014-04-20 16:43:37

标签: javascript jquery html

我使用以下代码来增加iframe高度。此代码在Mozilla和IE中运行良好,但在Google Chrome中无效。

<script type="text/javascript">
function calcHeight()
{
    the_height = document.getElementById('the_iframe').contentWindow.document.body.scrollHeight;
    document.getElementById('the_iframe').height = the_height + 35;
}
</script>    

<iframe src="indexframe.html" id="the_iframe" onLoad="calcHeight();" name="home_frame" width="100%" frameborder="0" ></iframe>

3 个答案:

答案 0 :(得分:0)

如果您使用的是jquery

$('#the_iframe').css({'height':(the_height+35)+'px'});

答案 1 :(得分:0)

在firefox

之外使用document.documentElement.scrollHeight
<iframe src="indexframe.html" id="the_iframe" onLoad="calcHeight();" name="home_frame" width="100%" frameborder="0" ></iframe>
<script type="text/javascript">
function calcHeight()
{

  the_height=document.documentElement.scrollHeight;
    document.getElementById('the_iframe').height=the_height+35;


}
</script>  

答案 2 :(得分:0)

跨浏览器的方式有点复杂

<iframe src="indexframe.html" id="the_iframe" name="home_frame" width="100%" frameborder="0" ></iframe>

<script type="text/javascript">
    var iframe = document.getElementById('the_iframe');

    if (iframe.addEventListener) {
        iframe.addEventListener('load', loader, false);
    } else if (iframe.attachEvent) {
        iframe.attachEvent("onload", loader);
    } else {
        iframe.onload = loader
    }

    function loader() {
        var D = iframe.contentDocument ? iframe.contentDocument :
        (iframe.contentWindow ? iframe.contentWindow.document : iframe.document),
        the_height = Math.max(
            D.body.scrollHeight, D.documentElement.scrollHeight,
            D.body.offsetHeight, D.documentElement.offsetHeight,
            D.body.clientHeight, D.documentElement.clientHeight
        );

        iframe.height = the_height+35;
    }   
</script>