1.不存在跨域情况
<iframe height="0px" id="outerPage" class= "outerPage" src="./test.html" onload="iframeload()"></iframe>
function iframeload() {
setTimeout(() => {
try {
const cIframe = document.getElementById("outerPage");
let aWindow = cIframe.contentWindow;
let aWindowHeight =
aWindow .document.documentElement.scrollHeight ||
aWindow .document.body.scrollHeight;
let doc = cIframe.contentDocument || cIframe.document;
let cHeight = Math.max(
doc.body.clientHeight,
doc.documentElement.clientHeight
);
let sHeight = Math.max(
doc.body. scrollHeight,
doc.documentElement.scrollHeight
);
let lheight = Math.max(cHeight, sHeight);
let finalHeight = Math.max(lheight, aWindowHeight );
var acheight = window.innerHeight;//屏幕可视宽度
console.log("sssss")
if(finalHeight<acheight)
$(".outerPage").css("height",finalHeight)
else
$(".outerPage").css("height",acheight)
} catch (e) {
//跨域获取不到
throw new Error("自定义错误setIframeHeight Error");
}
}, 1000);
}
2.存在跨域情况 使用postmessage传值
(1)引入页面
<script type="text/javascript">
var h = document.body.scrollHeight;
window.parent.postMessage(h+"", '*');
</script>
(2)iframe页面
<iframe height="0px" id="outerPage" class= "outerPage" src="http://192.168.1.22:8080/in.html" ></iframe>
window.addEventListener('message', function (e) {
console.log(e.data);
document.getElementById('outerPage').style.height=e.data+"px"
}, false)