我正在開發相似iGoogle的應用程序。 使用iframe顯示其餘應用程序(在其餘域上)的內容。 javascript
如何調整iframe的大小以適合iframe內容的高度? css
我試圖破譯Google使用的javascript,可是它被混淆了,到目前爲止,在網絡上搜索毫無結果。 html
更新:請注意,內容是從其餘域加載的,所以適用同源策略 。 java
使用jQuery的最簡單方法: shell
$("iframe") .attr({"scrolling": "no", "src":"http://www.someotherlink.com/"}) .load(function() { $(this).css("height", $(this).contents().height() + "px"); });
這是一種經過iframe的src屬性在json中添加信息的jQuery方法。 這是一個演示,調整大小並滾動此窗口。.帶有json的結果url看起來像這樣... http://fiddle.jshell.net/zippyskippy/RJN3G/show/#{docHeight:5124,windowHeight:1019,scrollHeight: 571}# json
這是小提琴的源代碼http://jsfiddle.net/zippyskippy/RJN3G/ 瀏覽器
function updateLocation(){ var loc = window.location.href; window.location.href = loc.replace(/#{.*}#/,"") + "#{docHeight:"+$(document).height() + ",windowHeight:"+$(window).height() + ",scrollHeight:"+$(window).scrollTop() +"}#"; }; //setInterval(updateLocation,500); $(window).resize(updateLocation); $(window).scroll(updateLocation);
這有點棘手,由於您必須知道什麼時候加載iframe頁面,而當您沒法控制其內容時就很難理解。 能夠在iframe中添加onload處理程序,可是我過去曾嘗試過這樣作,而且它在瀏覽器中的行爲也大不相同(不要猜想誰是最煩人的...)。 您可能必須將一個函數添加到iframe頁面中,以執行調整大小並將某些腳本注入到內容中,以監聽加載事件或調整大小事件,而後調用上一個函數。 我正在考慮向頁面添加功能,由於您想確保其安全性,可是我不知道這樣作會多麼容易。 安全
我相信這件事應該起做用。 網絡
parent.document.getElementById(iFrameID).style.height=framedPage.scrollHeight;
在iframe內容上加載時將其加載。 函數
<html> <head> <script> function frameSize(id){ var frameHeight; document.getElementById(id).height=0 + "px"; if(document.getElementById){ newheight=document.getElementById(id).contentWindow.document.body.scrollHeight; } document.getElementById(id).height= (frameHeight) + "px"; } </script> </head> <body> <iframe id="frame" src="startframe.html" frameborder="0" marginheight="0" hspace=20 width="100%" onload="javascript:frameSize('frame');"> <p>This will work, but you need to host it on an http server, you can do it locally. </p> </body> </html>