IFrame自适应高与contentWindow

本文介绍了一种使用JavaScript调整iframe元素高度的方法,确保iframe能够根据其内部内容自动调整大小,同时保持页面布局的整洁。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

<script type="text/javascript">
    function autoFixIfm()
    {
        var yocityAd= document.getElementById('yocityAd');       
        yocityAd.height=yocityAd.contentWindow.document.body.scrollHeight+5;
        yocityAd.width=yocityAd.contentWindow.document.body.scrollWidth+5;
    }
    </script>

 

<iframe id="yocityAd" name="yocityAd" src="Iframe/Index.aspx" width="100%" height="500" marginwidth="0" marginheight="0" scrolling="auto" frameborder="0" onload="autoFixIfm()"></iframe>

一定要加contentWindow, 不则是当前的document.body.scrollHeight

 

contentWindow Property

Internet Development Index


Retrieves the window object of the specified frame or iframe.

Syntax

HTMLN/A
Scripting[ oWindow = ] document.all.object.contentWindow

Possible Values

oWindowObject that receives the window object.

The property is read-only. The property has no default value.

Remarks

This property is useful if you do not know the id of the frame or iframe you are accessing through a collection.

=============================================

其子窗口中加入以下代码即可

 

    autoFixIframe: function(){
        try
        {
            if(window!=parent)
            {
                var commentIfrm = parent.document.getElementById("yocityAd");
                if(commentIfrm.contentWindow==window)
                {
                    var h1=0, h2=0, d=document, dd=d.documentElement;
                    commentIfrm.parentNode.style.height = commentIfrm.offsetHeight +"px";
                    commentIfrm.style.height = "10px";

                    if(dd && dd.scrollHeight) h1=dd.scrollHeight;
                    if(d.body) h2=d.body.scrollHeight;
                    var h=Math.max(h1, h2);

                    if(document.all){h += 4;}
                    if(window.opera){h += 1;}
                    commentIfrm.style.height = commentIfrm.parentNode.style.height = h +"px";
                }
               
            }
        }
        catch (ex){}
    }

 

    if(window.attachEvent)
    {
        window.attachEvent("onload",  iframeAutoFit);
    }
    else if(window.addEventListener)
    {
        window.addEventListener('load',  iframeAutoFit,  false);
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值