不要把頁面放到本地,不然會報錯,並且實現不了自適應高度的功能,
報錯:Blocked a frame with origin "null" from accessing a cross-origin frame;
原因:跨頁面操作涉及域的概念(origin),錯誤的意思是:未捕獲的安全錯誤:阻止了一個域為null的frame頁面訪問另一個域為null的頁面。代碼運行時在本地直接用瀏覽器打開的,地址欄是file:///的頁面,只需改為localhost訪問就行。
第一種:(在引入iframe的頁面加上)
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('iframe'));
};
第二種:
在引入iframe的頁面加上:
$("#iframe").load(function(){
var mainheight = $(this).contents().find("body").height()+30;
$(this).height(mainheight);
});
在子頁面加上:
$(window.parent.document).find("#iframe").load(function(){
var main = $(window.parent.document).find("#iframe");
var thisheight = $(document).height()+30;
main.height(thisheight);
});
例子:
<html lang="sv"><head> <meta charset="utf-8"> <title>Iframe height demo</title> <script src="jquery.js"></script> <style media="screen,print"> #body { width:70em; max-width:100%; margin:0 auto; } iframe { width:100%; margin:0 0 1em; border:0; } </style> <script> 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('iframe')); }; </script> </head> <body> <div id="body"> <h1>Iframe height demo</h1> <h2><code>iframe</code> <strong>without</strong> height adjustment</h2> <iframe src="child.html"></iframe> <h2><code>iframe</code> <strong>with</strong> height adjustment</h2> <iframe src="child.html" frameborder="0" id="iframe"></iframe> <div id="labfooter"> </div> </div> </body> </html>