前言
有时候,我们会使用 iframe标签,将前端分离项目无感的嵌入 如以Freemark为主体较老的项目中。
我们知道,当iframe内部内容比父页面所指定的宽高大的时候,会出现滚动框。
所以,让iframe的宽高能根据自身内容自动改变,就成了一个必须要解决的问题。
使用HTML5中新定义的window.postMessage 可以实现跨window通信。
demo效果
演示地址: www.mixvjiezi.xyz/demo/iframe

我们要的效果如上图所示。

黄色区域 是通过 iframe标签引入 的body.html部分。
index.html :
<!DOCTYPE html>
<html lang="en">
<script src="https://code.jquery.com/jquery-3.1.1.min.js">
var $ = window.jQuery;
</script>
<style>
.header{
width: 100%;
min-width: 1260px;
height: 70px;
background-color: red;
box-shadow: 0 0 5px black;
border-radius: 10px;
}
.center{
width: 1560px;
height: 1470px;
margin: 20px auto;
}
.iframe{
width: 250px;
height: 250px;
margin: 20px 0 0 40px;
}
.left-nav{
width: 200px;
height: 1470px;
background-color: blue;
float: left;
margin-top: 10px;
box-shadow: 0 0 5px black;
border-radius: 10px;
} </style>
<head>
<meta charset="utf-8" />
<title>css study</title>
</head>
<body>
<div class="header">
</div>
<div class="center">
<div class="left-nav"></div>
<iframe class="iframe" id="shopIframeId" src="./body.html" width="100%" height="100%" scrolling="no" frameborder="0"></iframe>
</div>
<script type="text/JavaScript">
window.addEventListener('message', e => {
if (e.data.type === 1) {
$('#shopIframeId').width(e.data.data.width + 50)
$('#shopIframeId').height(e.data.data.height + 50)
}
});
</script>
</body>
</html>
body.html:
<!DOCTYPE html>
<html lang="en">
<script src="https://code.jquery.com/jquery-3.1.1.min.js">
var $ = window.jQuery;
</script>
<style>
.box{
width: 200px;
height: 200px;
box-shadow: 0 0 5px black;
border-radius: 10px;
background-color: yellow;
}
</style>









