---
title: "IFrame自适应高与contentWindow "
author: "leyoo"
date: "2010-10-11T10:20:06Z"
tags: []
categories: ["编程语言"]
slug: "iframe-contentwindow"
draft: false
lastmod: "2010-10-27T14:39:14Z"
id: 781095
url: "https://leyoo.iteye.com/blog/781095"
---

IFrame自适应高与contentWindow  
 

<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

HTML N/A 
Scripting  document.all.object.contentWindow 

Possible Values

oWindow Object 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);
    }