javascript控制iframe自適應高度例子

來源:互聯網
上載者:User

iframe有一個煩人的問題,就是在沒有設定高度的情況下,被嵌套區會顯示一大片空白,有時候設定了高度也不行,後來用JavaScript輕鬆解決了iframe自適應高度的問題,下面把經驗和具體方法分享出來。
為了示範方便,這裡需要2個頁面,一個是被iframe的頁,一個是母頁面,先來看母頁面,也就是有iframe代碼的頁面:

 代碼如下 複製代碼

<html>
<head>
<title>iframe自適應載入的網頁高度</title>
</head>
<body>
<iframe src="iframe.htm"></iframe>
</body>
</html>

被iframe的頁面:假設檔案名稱是:iframe.htm,這個檔案裡的代碼為:

 代碼如下 複製代碼

<html>
<head>
<title>iframe自適應網頁高度</title>
<script type="text/javascript">
function iframeAutoFit()
{
    var ex;
    try
    {
        if(window!=parent)
        {
            var a = parent.document.getElementsByTagName("IFRAME");
            for(var i=0; i<a.length; i++) //author:meizz
            {
                if(a[i].contentWindow==window)
                {
                    var h1=0, h2=0;
                    if(document.documentElement&&document.documentElement.scrollHeight)
                    {
                        h1=document.documentElement.scrollHeight;
                    }
                    if(document.body) h2=document.body.scrollHeight;
                    var h=Math.max(h1, h2);
                    if(document.all) {h += 4;}
                    if(window.opera) {h += 1;}
                    a[i].style.height = h +"px";
                }
            }
        }
    }
    catch (ex){}
}
if(document.attachEvent)
{
    window.attachEvent("onload",  iframeAutoFit);
    window.attachEvent("onresize",  iframeAutoFit);
}
else
{
    window.addEventListener('load',  iframeAutoFit,  false);
    window.addEventListener('resize',  iframeAutoFit,  false);
}
</script>
</head>
<body>
<table border="1" width="200" style="height: 400px; background-color: yellow">
    <tr>
        <td>iframe自適應載入網頁的高度(多瀏覽器安全色,支援XHTML)</td>
    </tr>
</table>
</body>
</html>

最後補充一個:iframe的高度/寬度,自適應內容。

 代碼如下 複製代碼

<mce:script   language= "Javascript "><!--
 
window.onload=function()
{
    parent.document.all("iframe1").style.height = document.body.scrollHeight;
    parent.document.all("iframe1").style.width = document.body.scrollWidth;
}
// --></mce:script>

注意在iframe.htm頁面中,要使用JS做些設定,這是比較關鍵的,若看不懂不要緊,你可直接把代碼複製到你被iframe的頁面中即可。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.