由於瀏覽器安全原因以下的contentDocument 和contentWindow 對象必須起一個頁面服務(通過域名或ip地址來訪問)並且得保證父頁面與子頁面是在同一域名下,不然是會報錯的
contentDocument 可以獲得iframe子窗口的document對象,兼容ie8+
contentWindow 這是個只讀屬性,返回指定的iframe的窗口對象。
在iframe加載完畢之后通過contentDocument 或者 contentWindow 這二個對象來獲取iframe子頁面的內容高度,從而來設置iframe的高度.再給iframe設置高度時子頁面的默認樣式margin要記得清除(不清楚是會有這個margin大小的誤差的,有這個margin的話子頁面的內容就無法全部顯示出來了).
iframe的父頁面
<iframe scrolling="no" id="main" name="main" frameborder="0" src="iframe子頁面1.html"></iframe>
<script type="text/javascript">
//根據ID獲取iframe對象
var ifr = document.getElementById('main');
ifr.onload = function() {
//解決滾動條不收縮
ifr.style.height = 0+'px';
var iDoc = ifr.contentDocument || ifr.contentWindow.document;
var height = iDoc.documentElement.clientHeight || iDoc.body.clientHeight;
console.log(iDoc.documentElement.clientHeight,iDoc.body.clientHeight);
ifr.style.height = height + 'px';
console.log(height);
}
</script>
