2013-08-27 32 views
18

我正在開發jQuery,我偶然發現了下一個問題:我在主頁面中添加了一個IFrame,我想從裏面重新調整它們的大小。我嘗試了一些想法,但沒有成功。如何從內部更改iframe的大小?

這裏是我的代碼:

的index.html

<html> 
    <head> 
     <title>Index</title> 
    </head> 
    <body> 
     <iframe id="myframe" src="frame.html" width="100px" height="100px"></frame> 
    </body> 
</html> 

frame.html

<html> 
    <head> 
     <title>IFrame</title> 
     <script> 
      document.width = 500; 
      document.height = 500; 
     </script> 
    </head> 
    <body> 
     <h2>My IFrame</h2> 
    </body> 
</html> 

回答

29

當你創建一個IFRAME瀏覽器會自動添加一個'window'對象主要頁面的'window'對象內的IFRAME。

您需要更改IFRAME的大小而不是文檔的大小。

試試這個代碼:

對於JavaScript

window.parent.document.getElementById('myframe').width = '500px'; 
window.parent.document.getElementById('myframe').height = '500px'; 

併爲jQuery

$('#myframe', window.parent.document).width('500px'); 
$('#myframe', window.parent.document).height('500px'); 
+6

我猜這無法從不同的域做了,對不對? – Anoyz

+3

是的,不同的域在Chrome中失敗並顯示以下消息:未捕獲的SecurityError:阻止了一個源於「http://anotherwebsite.com」的框架訪問源自「http://mywebsite.com」的框架。協議,域和端口必須匹配。「# – Zanon

+0

我沒有收到該錯誤。作爲一個概念驗證:http://jperelli.com.ar/covert_channel_iframe_resize/ – jperelli

-1
function setHeight() { 
    parent.document.getElementById('the-iframe-id').style.height = document['body'].offsetHeight + 'px'; 
} 

使用Javascript

document.getElementById("ifr").height= "500px"; 
document.getElementById("ifr").width= "500px"; 
另一種方式

DEMO JSFIDDLE

13

如果這兩個網頁位於同一個域(或者,如果你設置文件甚至子域。域可能,沒有測試它),你可以簡單地從JavaScript(或jQuery)設置它:

window.parent.document.getElementById('myframe').width = '500px';

如果你的網頁在不同的結構域的一種解決辦法是在被調用的iFrame(學分馬蒂·穆利根)的頁面添加事件偵聽器:

<html> 
 
<head> 
 
    <title>Index</title> 
 
\t <script src="/js/jquery/js/jquery.1.10.2.min.js"></script> 
 
\t <script> 
 
\t \t window.addEventListener('message', function(e) { 
 
\t \t \t debugger; 
 
\t \t var iframe = $("#myIframe"); 
 
\t \t var eventName = e.data[0]; 
 
\t \t var data = e.data[1]; 
 
\t \t switch(eventName) { 
 
\t \t \t case 'setHeight': 
 
\t \t \t iframe.height(data); 
 
\t \t \t break; 
 
\t \t } 
 
\t \t }, false); 
 
\t </script> 
 
</head> 
 
<body> 
 
    <iframe id="myIframe" src="http://hofvanzeeland.net/frame.html" width="100px" height="100px" border="1"></frame> 
 
</body> 
 
</html>

和從所述iFrame內容觸發它(frame.html):

<html> 
 
    <head> 
 
     <title>IFrame</title> \t \t 
 
     <script>    
 
\t \t \t function resize() { 
 
\t \t \t var height = document.getElementsByTagName("html")[0].scrollHeight; 
 
\t \t \t window.parent.postMessage(["setHeight", height], "*"); 
 
\t \t \t } 
 
     </script> 
 
    </head> 
 
    <body> 
 
     <h2>My IFrame</h2> 
 
\t \t <a href="#" onclick="resize()">Click me</a> 
 
    </body> 
 
</html>

+0

非常好解釋!爲我工作! –

+0

喲在這裏要注意的巨大安全風險 - 通過[MDN](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage): ** tl; dr **如果您不希望接收來自其他站點的消息,請勿爲消息事件添加任何事件偵聽器,始終驗證發件人身份,並且在使用postMessage將數據發送到其他窗口時始終指定確切的目標源,而不是*。 –