js實現的真正的iframe高度自適應(相容IE,FF,Opera)_javascript技巧

來源:互聯網
上載者:User
找到了下面這個js
複製代碼 代碼如下:

function SetCwinHeight(obj)
{
var cwin=obj;
if (document.getElementById)
{
if (cwin && !window.opera)
{
if (cwin.contentDocument && cwin.contentDocument.body.offsetHeight)
cwin.height = cwin.contentDocument.body.offsetHeight + 20;
else if(cwin.Document && cwin.Document.body.scrollHeight)
cwin.height = cwin.Document.body.scrollHeight + 10;
}
}
}

然後……
進入了測試過程(調用很簡單,先略過)
1.IE ---通過 但是高度還是有稍微的差距,很小,捲軸還在
2.FF --- 通過 與IE一樣,有小差距
3.Opera --- 看那個JS的條件就知道,通不過的
但主流瀏覽器至少要通過這三項撒!!!
於是,還是Google
搜尋 各瀏覽器在處理 document.scrollHeight 或者 offsetHeigth時的特殊現象
發現,Opera瀏覽器在處理iframe內容的時候,用的是contentWindow
而處理內容高度的時候,卻與IE一致
從而,有了下面這段js
複製代碼 代碼如下:

<html>
<head>
<script>
function SetCwinHeight(obj)
{
var cwin=obj;
if (document.getElementById)
{
if (cwin && !window.opera)
{
if (cwin.contentDocument && cwin.contentDocument.body.offsetHeight)
cwin.height = cwin.contentDocument.body.offsetHeight + 20; //FF NS
else if(cwin.Document && cwin.Document.body.scrollHeight)
cwin.height = cwin.Document.body.scrollHeight + 10;//IE
}
else
{
if(cwin.contentWindow.document && cwin.contentWindow.document.body.scrollHeight)
cwin.height = cwin.contentWindow.document.body.scrollHeight;//Opera
}
}
}
</script>
</head>
<body>
<iframe src="20103622440.html" onload="SetCwinHeight(this);" width="600px">
</body>
</html>

這樣一來,總算把這三個瀏覽器給適應了
做為程式員,還是要細心點
再測試一下
OK...3個瀏覽器均正常顯示,也無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.