vue的iframe自适应高度
时间: 2023-05-10 09:01:42 浏览: 153
vue中使用iframe嵌入其他页面,可以通过以下步骤实现自适应高度:
1. 在iframe中设置滚动条为no,并给iframe添加一个id标识。
2. 在父组件中引用该iframe,并使用$refs获取该元素。
3. 监听iframe的onload事件,获取iframe内部内容的高度,然后将该高度重新赋值给iframe的高度。
代码实现如下:
<template>
<iframe ref="myIframe" src="https://www.example.com" scrolling="no"></iframe>
</template>
<script>
export default {
mounted() {
window.addEventListener('resize', this.handleResize);
this.$refs.myIframe.onload = () => {
this.handleResize();
};
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
const iframe = this.$refs.myIframe;
const innerDoc = iframe.contentDocument || iframe.contentWindow.document;
const contentHeight = Math.ceil(innerDoc.documentElement.scrollHeight);
iframe.style.height = `${contentHeight}px`; // 设置iframe高度
}
}
}
</script>
通过实时监听iframe内部内容的高度变化,重新计算并设置iframe的高度,可以实现自适应高度的效果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)