jQuery实现iframe高度自适应(兼容IE6,7,8)

2011年3月24日 由 chunterg 留言 »

网上有很多iframe自适应的方法,但基本都是基于body或document的,当body被撑大后,不能变小,这样就当iframe内部页面的dom变化时,iframe的大小不会跟着变化

我的方法是把在内容外面包在一个层(div)里,通过获取这个层(div)的高度来控制iframe的高度。

Demo演示
注:本次探讨只涉及同域iframe,跨域iframe的自适应接下去再尝试。

代码如下:
父窗口代码:

<!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>
</head>
<body>
 <div style="height:200px"></div>
 <iframe id="iframe_1" src="iframe-inside-content.html" width="100%" frameborder="no" border="0" scrolling="no"></iframe>
</body>
</html>

子窗口代码:

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
 $(document).ready(function(){
 /*
 * $("#wrap").height()为总包裹容器层的高度
 */
 $(window.parent.document).find('#iframe_1').height($("#wrap").height());
 })
/*
 * 隐藏内容使iframe高度变小
 */
function hideDiv(){
 $("#content").hide();
 $(window.parent.document).find('#iframe_1').height($("#wrap").height());
}
/*
 * 隐藏内容使iframe高度变大
 */
function showDiv(){
 $("#content").show();
 $(window.parent.document).find('#iframe_1').height($("#wrap").height());
}
</script>
<style>
*{margin:0;paddding:0;}/*重置默认的间距*/
body{background:transparent;background-color:#eee;height:100%;}
#content{height:1000px;background-color:#ddd;margin:50px;}
/*
 * 如果#content内容有浮动层,即使用了float,
 * 那#wrap也必须用float,不然#wrap不会包含#content的高度
 * #wrap{float:left}
 * #content{float:left}
 */
</style>
</head>
<body>
 <div id="wrap">
 <a href="#" onclick="hideDiv();">隐藏DIV</a>
 <a href="#" onclick="showDiv();">显示DIV</a>
 <div id="content">div content</div>
 </div>
</body>
</html>

1条评论

  1. lucker 说道:

    还是不兼容火狐,谷歌兼容

发表评论