实现iframe框架页面高度自动刷新的JavaScript方案
作者:青柠时间:2026-10-27 16:20:45浏览:226
本文介绍一种通过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>作者最新文章
ES6模块化中js文件怎么用import和export交互
2026-11-05 17:00:48
JS读取本地文件时报错或无响应的常见原因
2026-11-05 16:32:31
let、const与var的区别:JavaScript变量声明最佳实践
2026-11-05 14:16:38
JS中直接定义静态二维数组的字面量写法
2026-11-05 14:16:08
JS 怎么查找字符串中所有匹配项的位置
2026-11-05 14:15:53
