最近遇到一個問題糾結死了,iframe總是不能高度自适應,去網上查有很多解答,但是總不能解決問題,根本無效
老是報錯
a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.
這句話大概意思是必須同一個域
我隻是做的HTML用iframe引用其他的HTML,這樣并不是同一個域,簡直笨死了,将其放到tomcat下測試了才可以,這才是在同一個域,用跨域也有解決辦法,不過暫未驗證,下面是倆參考網址
iframe高度自适應 JavaScript跨域總結與解決辦法
以下是核心代碼(都是在父檔案裡)
<iframe id="iframe" name="iframe" src="../index.jsp" width="100%" frame scrolling="no" οnlοad="setIframeHeight(this)"></iframe>
<script type="text/javascript" language="javascript">
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;
}
}
};
</script>
注意!js不要寫在head裡,不起作用,放到body裡面
這也是iframe自适應的一種方法
<div id="index-content">
<iframe id="iframe" src="login/register.html" width="100%" height="800px" onLoad="iFrameHeight()" frame marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div>
<script type="text/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>
參考于下面網站,裡面還有很多方法,也還沒驗證
http://www.jb51.net/article/15780.htm