iframe高度自适应的解决方案
使用场景:
通过Iframe来解决项目嵌套问题时会碰到iframe的高度自适应的问题;
正常情况下的iframe:会出现一个滚动条影响美观
情况1:不存在跨域情况时的解决方案
<iframe name="outerPage" onload="iframeload()" src="./test.html" name="myFrame" scrolling="auto" frameborder="0"
id="outerPage" :style="{ 'min-width': '100%', 'min-height': '100%' }"></iframe>
<script>
function iframeload () {
try {
const cIframe = document.getElementById('outerPage')
let aWindow = cIframe.contentWindow
let aWindowHeight = aWindow.document.documentElement.scrollHeight
cIframe.style.height = aWindowHeight + 'px'
} catch (e) {
//跨域获取不到
throw new Error(e,'自定义错误setIframeHeight Error')
}
}
</script>
情况1:存在跨域情况时的解决方案
//引入iframe的页面
<iframe name="outerPage" src="http://localhost:9006/#/home/homePage" name="myFrame"
scrolling="no" frameborder="0" id="outerPage" style="width:100%"></iframe>
<script>
window.addEventListener('message', (e) => {
const cIframe = document.getElementById('outerPage')
cIframe.style.height = e.data.text + 'px'
})
</script>
//被引入的iframe页面:发送事件
mounted() {
this.$nextTick(() => {
// 等子页面渲染好了之后,获取高度
setTimeout(() => {
const viewHeight = document.getElementById("app").scrollHeight;
window.parent.postMessage(
{
code: "iframeheght",
text: viewHeight
},
"*"
);
}, 1000);
});
},