iframe自适应高度问题
1、不跨域
iframe的页面直接修改包裹着它的iframe的高度就行
2、跨域
用postMessage
https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage
下面是demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<iframe src="http://127.0.0.1:4321/b.html" frameborder="0" width="100%" id="iframe-b"></iframe>
<script type="text/javascript">
window.onload = function() {
window.addEventListener('message', function(event) {
if (event.origin === "http://127.0.0.1:4321") {
document.getElementById("iframe-b").style.height = event.data + "px";
console.log(event.data)
}
}, false);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
.hello {
width: 200px;
height: 500px;
background-color: red;
}
</style>
<body>
<div class="hello">
</div>
<script type="text/javascript">
// window.onload = function() {
// var h = document.body.scrollHeight;
// parent.postMessage(h, "http://127.0.0.1:1234");
// }
setTimeout(() => {
var h = document.body.scrollHeight;
parent.postMessage(h, "http://127.0.0.1:1234");
}, 500);
</script>
</body>
</html>