iframe自动适应高度(完美自适应高度嵌套代码),兼容目前主流浏览器
时间: 2023-08-01 21:01:40 浏览: 144
要实现iframe的自动适应高度,可以通过以下步骤进行操作,以保证兼容主流浏览器。
首先,需要在iframe的源文件中添加一段脚本代码来实现自适应高度的功能。具体代码如下所示:
```html
<script type="text/javascript">
function autoResize() {
var iframe = parent.document.getElementById("your-iframe-id");
if (iframe) {
iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
}
}
window.onload = autoResize;
</script>
```
上述代码中的"your-iframe-id"需要替换为你实际的iframe元素的id。
然后,在iframe的父页面中,需要通过以下代码来监听iframe内容的变化,并触发自适应高度的函数:
```html
<script type="text/javascript">
function setIframeHeight() {
var iframe = document.getElementById("your-iframe-id");
iframe.onload = function() {
this.style.height = this.contentWindow.document.body.scrollHeight + 'px';
};
}
window.onload = setIframeHeight;
</script>
```
同样,上述代码中的"your-iframe-id"需要替换为实际的iframe元素的id。
这样,当iframe的内容发生变化时,它的高度会自动适应内容的高度。
最后,在需要插入iframe的地方,添加以下代码即可:
```html
<iframe id="your-iframe-id" src="your-source-url"></iframe>
```
其中,"your-iframe-id"为iframe元素的id,"your-source-url"为iframe显示的源文件的URL。
以上操作可以实现iframe的自适应高度,并兼容目前主流浏览器。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)