Javascript使iframe自適應高度執行個體

來源:互聯網
上載者:User

工作中我們遇到了iframe嵌入頁面高度自適應的問題。因為我們不知道所載入的iframe內容頁面會有多高,又不想在頁面上出現難看的捲軸,這個時候我們可以使用Javascript來動態讓iframe自適應高度。


準備工作

我們準備一個首頁面a.html,以及兩個用於嵌入iframe的頁面分別為iframeH.html和iframeH1.html,內容可以自己隨便加,實際應用中可能是後台產生的內容。
為了示範,我們在首頁面a.html中加入如下代碼:
 
<div class="opt_btn">
    <button onclick="getData('iframeH');">載入內容1</button>
    <button onclick="getData('iframeH2');">載入內容2</button>
</div>
<iframe src="iframeH.html" id="ifrm" frameborder="0" width="100%" scrolling="no" marginheight="0" marginwidth="0" onLoad="setIframeHeight(this.id)"></iframe>

我們要實現的是,分別點擊兩個按鈕,iframe中載入不同的內容,iframe中不能出現捲軸。

Javascript

首先我們使用Javascript動態改變iframe的src值,即分別點擊兩個按鈕時,iframe載入不同的頁面內容。代碼中按鈕button分別調用了自訂函數getData()就實現了切換內容的效果。
 
function getData(ifm){
    document.getElementById("ifrm").src = ifm+'.html';
}

然後,我們來關注iframe裡的內容,因為我們事先不知道iframe的內容高度,如果先設定好iframe的高度height值,很可能當頁面內容超長時會出現捲軸,這不是我們想要的。那麼我們使用Javascript來動態擷取iframe頁面高度,然後設定iframe的高度。
在iframe完全載入後即onload,調用setIframeHeight(),iframe內容載入完成後,可擷取iframe的高度值,然後重新設定iframe的高度,以下是整理好的代碼:
 
function setIframeHeight(id) {
    var ifrm = document.getElementById(id);
    var doc = ifrm.contentDocument? ifrm.contentDocument: 
        ifrm.contentWindow.document;
    ifrm.style.visibility = 'hidden';
    ifrm.style.height = "10px"; // reset to minimal height ...
    ifrm.style.height = getDocHeight( doc ) + 4 + "px";
    ifrm.style.visibility = 'visible';
}
 
function getDocHeight(doc) {
    doc = doc || document;
    var body = doc.body, html = doc.documentElement;
    var height = Math.max( body.scrollHeight, body.offsetHeight, 
        html.clientHeight, html.scrollHeight, html.offsetHeight );
    return height;
}

經典代碼 iFrame 自適應高度,在IE6/IE7/IE8/Firefox/Opera/Chrome/Safari通過測試。


<iframe src="http://www.111cn.net/" id="iframepage" name="iframepage" frameBorder=0 scrolling=no width="100%" onLoad="iFrameHeight()" ></iframe>Javascript代碼:
<script type="text/javascript" language="javascript">
function iFrameHeight() {
var ifm= document.getElementById("iframepage");
var subWeb = document.frames ? document.frames["iframepage"].document : ifm.contentDocument;
if(ifm != null && subWeb != null) {
ifm.height = subWeb.body.scrollHeight;
}
}
</script>

下面這個相容性更好一些

<script language="javascript" type="text/javascript">
function dyniframesize(down) {
var pTar = null;
if (document.getElementById){
pTar = document.getElementById(down);
}
else{
eval('pTar = ' + down + ';');
}
if (pTar && !window.opera){
//begin resizing iframe
pTar.style.display="block"
if (pTar.contentDocument && pTar.contentDocument.body.offsetHeight){
//ns6 syntax
pTar.height = pTar.contentDocument.body.offsetHeight +20;
pTar.width = pTar.contentDocument.body.scrollWidth+20;
}
else if (pTar.Document && pTar.Document.body.scrollHeight){
//ie5+ syntax
pTar.height = pTar.Document.body.scrollHeight;
pTar.width = pTar.Document.body.scrollWidth;
}
}
}
</script>
<iframe src ="/default2.aspx" frameborder="0" marginheight="0" marginwidth="0" frameborder="0" scrolling="auto" id="ifm" name="ifm" onload="javascript:dyniframesize('ifm');" width="100%">
</iframe>

iframe內容未知,高度可預測

這個時候,我們可以給它添加一個預設的CSS的min-height值,然後同時使用javascript改變高度。常用的相容代碼有:


// document.domain = "caibaojian.com";
function setIframeHeight(iframe) {
if (iframe) {
var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;
if (iframeWin.document.body) {
iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;
}
}
};

window.onload = function () {
setIframeHeight(document.getElementById('external-frame'));
};

只要修改以上的iframe的ID即可了。或者你可以直接在iframe裡面寫代碼,我們一般為了不汙染html代碼,建議使用上面的代碼。

<iframe src="backtop.html" frameborder="0" scrolling="no" id="external-frame" onload="setIframeHeight(this)"></iframe>

多個iframe的情況下

<script language="javascript">
//輸入你希望根據頁面高度自動調整高度的iframe的名稱的列表
//用逗號把每個iframe的ID分隔. 例如: ["myframe1", "myframe2"],可以只有一個表單,則不用逗號。
//定義iframe的ID
var iframeids=["test"];
//如果使用者的瀏覽器不支援iframe是否將iframe隱藏 yes 表示隱藏,no表示不隱藏
var iframehide="yes";
function dyniframesize()
{
var dyniframe=new Array()
for (i=0; i<iframeids.length; i++)
{
if (document.getElementById)
{
//自動調整iframe高度
dyniframe[dyniframe.length] = document.getElementById(iframeids[i]);
if (dyniframe[i] && !window.opera)
{
dyniframe[i].style.display="block";
if (dyniframe[i].contentDocument && dyniframe[i].contentDocument.body.offsetHeight) //如果使用者的瀏覽器是NetScape
dyniframe[i].height = dyniframe[i].contentDocument.body.offsetHeight;
else if (dyniframe[i].Document && dyniframe[i].Document.body.scrollHeight) //如果使用者的瀏覽器是IE
dyniframe[i].height = dyniframe[i].Document.body.scrollHeight;
}
}
//根據設定的參數來處理不支援iframe的瀏覽器的顯示問題
if ((document.all || document.getElementById) && iframehide=="no")
{
var tempobj=document.all? document.all[iframeids[i]] : document.getElementById(iframeids[i]);
tempobj.style.display="block";
}
}
}
if (window.addEventListener)
window.addEventListener("load", dyniframesize, false);
else if (window.attachEvent)
window.attachEvent("onload", dyniframesize);
else
window.onload=dyniframesize;
</script>
示範三

針對知道的iframe的ID調用

function iframeAutoFit(iframeObj){
setTimeout(function(){if(!iframeObj) return;iframeObj.height=(iframeObj.Document?iframeObj.Document.body.scrollHeight:iframeObj.contentDocument.body.offsetHeight);},200)
}
示範四

內容寬度變化的iframe高度自適應

<iframe src="backtop.html" frameborder="0" scrolling="no" id="test" onload="this.height=100"></iframe>
<script type="text/javascript">
function reinitIframe(){
var iframe = document.getElementById("test");
try{
var bHeight = iframe.contentWindow.document.body.scrollHeight;
var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
var height = Math.max(bHeight, dHeight);
iframe.height = height;
console.log(height);
}catch (ex){}
}
window.setInterval("reinitIframe()", 200);
</script>


開啟調試運行視窗可以看到運行。

跨域下的iframe自適應高度

跨域的時候,由於js的同源策略,父頁面內的js不能擷取到iframe頁面的高度。需要一個頁面來做代理。
方法如下:假設www.a.com下的一個頁面a.html要包含www.b.com下的一個頁面c.html。
我們使用www.a.com下的另一個頁面agent.html來做代理,通過它擷取iframe頁面的高度,並設定iframe元素的高度。

a.html中包含iframe:

<iframe src="http://www.b.com/c.html" id="Iframe" frameborder="0" scrolling="no" style="border:0px;"></iframe>
在c.html中加入如下代碼:

<iframe id="c_iframe"  height="0" width="0"  src="http://www.a.com/agent.html" style="display:none" ></iframe>
<script type="text/javascript">
(function autoHeight(){
var b_width = Math.max(document.body.scrollWidth,document.body.clientWidth);
var b_height = Math.max(document.body.scrollHeight,document.body.clientHeight);
var c_iframe = document.getElementById("c_iframe");
c_iframe.src = c_iframe.src + "#" + b_width + "|" + b_height;  // 這裡通過hash傳遞b.htm的寬高
})();
</script>

最後,agent.html中放入一段js:

<script type="text/javascript">
var b_iframe = window.parent.parent.document.getElementById("Iframe");
var hash_url = window.location.hash;
if(hash_url.indexOf("#")>=0){
var hash_width = hash_url.split("#")[1].split("|")[0]+"px";
var hash_height = hash_url.split("#")[1].split("|")[1]+"px";
b_iframe.style.width = hash_width;
b_iframe.style.height = hash_height;
}
</script>
agent.html從URL中獲得寬度值和高度值,並設定iframe的高度和寬度(因為agent.html在www.a.com下,所以操作a.html時不受JavaScript的同源限制)

注意本文談到的iframe自適應以及上一篇文章中的iframe操作dom都是基於同域下的操作,即在相同網域名稱下實現的,那麼如果在不同網域名稱下即跨域是不能這樣操作的。關於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.