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'));};如果在同一個頂級域名下,不同子域名之間互通信息,設置document.domain =「 caibaojian.com」只要修改以上的iframe的ID就可以了。不汙染html代碼,建議使用上面的代碼。
<iframe src="backtop.html" frameborder="0" scrolling="no" id="external-frame" onload="setIframeHeight(this)"></iframe>2、多個iframe的情況下<script language="JavaScript">var iframeids=["test"];var iframehide="yes";function dyniframesize(){var dyniframe=new Array()for (i=0; i<iframeids.length; i++){if (document.getElementById){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) dyniframe[i].height = dyniframe[i].contentDocument.body.offsetHeight;else if (dyniframe[i].Document && dyniframe[i].Document.body.scrollHeight) dyniframe[i].height = dyniframe[i].Document.body.scrollHeight;}}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);elsewindow.onload=dyniframesize;</script>3、針對知道的iframe的ID調用function iframeAutoFit(iframeObj){setTimeout(function(){if(!iframeObj) return;iframeObj.height=(iframeObj.Document?iframeObj.Document.body.scrollHeight:iframeObj.contentDocument.body.offsetHeight);},200)}4、內容寬度變化的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>5、跨域下的iframe自適應高度跨域的時候,由於js的同源策略,父頁面內的js無法獲取到iframe頁面的高度。需要一個頁面來做代理。方法如下:假設www.a.com下一個一個頁面a.html要包含我們使用www.a.com下一個另一個頁面agent.html來做代理,通過它獲取iframe頁面的高度,並設置iframe元素的高度。html中包含iframe:
<iframe src="http://www.b.com/c.html" id="Iframe" frameborder="0" scrolling="no"></iframe>在c.html中加入如下代碼:
<iframe id="c_iframe" height="0" width="0" src="http://www.a.com/agent.html" ></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; })();</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的類似限制)
6、postMessage + window.name實現跨域iframe高度自適應兼容版我們知道HTML5 PostMessage不支持IE8以下的瀏覽器跨域,於是我想到了window.name支持ie6和ie7的方案,那麼能否把這兩種合併起來,變成一種全兼容的跨域方案呢?還別說,真有人能做到。
html5 postMessage實現跨域postMessage是html5的一個新功能,可以實現不同域名之間的通信,通過給postMessage方式發送數據,監聽則通過在父子窗口上添加onmessage事件進行。缺點也就很明顯了,只有支持html5的瀏覽器才支持這種跨域方式,像IE6、7當然就拒之門外了!
window.name實現跨域window.name實現跨域也是一個比較老的問題,之前kejun寫過一個演示,可是給的卻是同域名的通信。其實kejun的實例中就是實現跨域的,不過他採用了同一個域名,而且過程比較崎嶇:
建立iframe,指定src為被跨域的頁面
被跨域文件修改window.name,將數據傳給window.name
將iframe.src修改為本域代理文件,然後就可以取到contentWindow.name
進行處理數據,清除iframe充分的運用了window.name因為頁面的URL改變而名稱不改變的特性。但是如果我們是自己用,還是可以的,而如果我們放出去要別人使用我們寫的東西,那樣學習成本太大。
多瀏覽器雙向跨域為了解決上面的問題,我們使用的方法就是如果支持postMessage的瀏覽器就使用postMessage,如果不支持的就採用window.name的方式,幸運的是在IE6、7中支持跨域設置window.name,而我們就可以簡單的通過window.name來跨域。
然後建立計時器來監聽window.name是否發生了變化,如果變化則接收並分析window.name,然後做請求。
演示和代碼:
<body> <div style="width:100%;border:1px solid green;"> <h3>this page from :<span id="host"></span></h3> <input type="text" value="" id="data" /><button id="btn" onclick="send();">提交</button> </div> <iframe id="iframeA" src="http://1.qdemo.sinaapp.com/cross-domain/client.html" style="border:1px solid #ff6600;width:100%;height:300px;"></iframe> <script type="text/javascript"> document.getElementById('host').innerHTML = location.host; function send(){ var val = document.getElementById('data').value; sendMessage(val); } (function(win, doc){ var ifr = doc.getElementById('iframeA').contentWindow; var cb = function(json){ alert(location.host+" get msg:"+json); }; var sendMessage = function(){ if(win.postMessage){ if (win.addEventListener) { win.addEventListener("message",function(e){ cb.call(win,e.data); },false); }else if(win.attachEvent) { win.attachEvent("onmessage",function(e){ cb.call(win,e.data); }); } return function(data){ ifr.postMessage(data,'*'); }; }else{ var hash = ''; setInterval(function(){ if (win.name !== hash) { hash = win.name; cb.call(win, hash); } }, 50); return function(data){ ifr.name = data; }; } }; win.sendMessage = sendMessage(); })(window, document);</script></body><body> <h3>this page from :<span id="host"></span></h3> <input type="text" value="" id="data" /><button id="btn" onclick="send();">提交</button> <ul> <li>firefox、chrome等高級瀏覽器採用html5 postMessage方法</li> <li>IE6 7等使用window.name方法</li> <li>支持雙向跨域,在chrome 13、firefox6、IE6+測試通過</li> <li>window.name可以通過data加隨機數方式,避免兩次提交的數據相同,本例沒做處理,所以如果不改變value值點擊提交是不會觸發alert的</li> <li><a href="cross-domain.zip">demo下載</a></li> </ul> <script type="text/javascript"> document.getElementById('host').innerHTML = location.host; function send(){ var val = document.getElementById('data').value; sendMessage(val); } (function(win, doc){ var ifr = win.parent; var cb = function(json){ alert(location.host+" get msg:"+json); }; var sendMessage = function(){ if(win.postMessage){ if (win.addEventListener) { win.addEventListener("message",function(e){ cb.call(win,e.data); },false); }else if(win.attachEvent) { win.attachEvent("onmessage",function(e){ cb.call(win,e.data); }); }
return function(data){ ifr.postMessage(data,'*'); }; }else{ var hash = ''; setInterval(function(){ if(win.name!==hash){ hash = win.name; cb.call(win,hash); } },50); return function(data){ ifr.name = data; }; } } win.sendMessage = sendMessage(); })(window, document);</script></body>基於上面的代碼,結合我上篇文章的演示,我們再來命名一個iframe自適應高度的解決方案。