实现iframe框架页面高度自动刷新的JavaScript方案

作者:青柠

时间:2026-10-27

浏览:225

本文介绍一种通过JavaScript脚本实现iframe框架页面高度自动刷新的方法。该方案在父页面index.htm中嵌入定时调用函数,每秒钟检测子页面内容高度并动态调整iframe的height属性。无需修改子页面代码,即可解决因内容变化导致的框架高度不匹配问题,提升页面展示效果。

文章目录
实现原理:

实现原理与优势

当加载index.htm页面时,系统会每隔1秒钟自动执行一次脚本来刷新框架页面的高度。


代码优点:

该方案仅需在index.html的框架页面中配置相关脚本,被加载的子页面无需进行任何额外设置。


代码实现

index.htm页面的具体代码实现如下所示:


具体代码片段如下:

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>首页</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div style="float: left; width: 740px; height:auto; border: 1px #808080 Solid; margin: 5px 0px 5px 10px;overflow: hide">
<iframe name="ifr_obj" id="ifr_obj" src="这里嵌套其它页面地址或者文件名" frameborder="0" width="100%" scrolling="no" title="框架页面"></iframe>
</div>
</body>
<script language="javascript" type="text/javascript">
function initIframeHeight() {
try {
var iframe = document.getElementById("ifr_obj");
if (iframe != null) {
if (iframe.contentWindow.document.body != null) {
var bHeight = iframe.contentWindow.document.body.scrollHeight;
var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
var height = Math.max(bHeight, dHeight);
iframe.height = height;
} 
} 
} 
} catch (ex) {
alert("加载框架页面高度时出错"+ex.toString());
} 
} 
window.setInterval("initIframeHeight()", 1000);
</script>
</html>

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章