为了解决iframe 自适应高高度的问题 已花了我不少时间,在网上找了好几种方法,可每种都有问题,在参考同事的方法后终于解决了所有问题,现在就把代码写出来和大家分享下,同时避免以后忘记。代码如下:
主页面代码:
<html>
<head>
<meta content="text/html; charset=utf-8" />
<title>iframe自适应高度</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function(){
// 加载时自适应高度
$("#mainFrame").load(function(){
var frameHeight = $(this).contents().find(".frameContent").height() + 10;
$(this).height(frameHeight);
})
var iframe = $("#mainFrame")
// 定时检测并更新iframe的高度
setInterval(function(){
var mainheight = iframe.contents().find("
.frameContent ").height()+10;
iframe.height(mainheight);
},0)
})
</script>
</head>
<body>
<a href="contentFrame1" target="mainFrame">页面1</a>
<a href="contentFrame2" target="mainFrame">页面2</a>
<iframe src="" id="mainFrame" name="mainFrame" frameborder="0" scrolling="no"></iframe>
</body>
</html>
(以下代码就不具体写了,只写内容部分)
页面1代码:
<div class="frameContent" style="height:500px; width:500px; border:1px solid #f00;">
页面2代码:
<div class="frameContent" style="height:800px; width:500px; border:1px solid #f00;">
以上的方法解决了
iframe.contentWindow.document.documentElement.scrollHeight 和直接使用
οnlοad="this.height=this.contentWindow.document.documentElement.scrollHeight" 只有在刷新后才能自适应高度的问题,其实这两个并不是自适应,只能获取最大高度来适应。如果知道这两种的解决方法,希望可以把详细的实现步骤写出来分享下,谢谢!