JQuery自适应IFrame高度(支持嵌套 兼容IE,ff,safafi,chrome)

复制代码 代码如下:

  function adjustIFramesHeightOnLoad(iframe) {

  var iframeHeight = Math.min(iframe.contentWindow.window.document.documentElement.scrollHeight, iframe.contentWindow.window.document.body.scrollHeight);

  $(iframe).height(iframeHeight);

  }

  失败的测试就不说了,来直接的。

  两个链接和iframe:

  

复制代码 代码如下:

  <li><a href="selfinfo.jsp" target="c-c-iframe" title="个人信息" >个人信息</a></li>

  <li><a href="modifypass.jsp" target="c-c-iframe" title="修改密码" >修改密码</a></li>

  <iframe src="init.jsp" id="c-c-iframe" name="c-c-iframe" width="500px;" frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe>

  js代码:

  

复制代码 代码如下:

  <script type="text/javascript">

  <!--

  $(function(){

  $("#c-c-iframe").load(function(){

  $(this).height($(this).contents().find("#content").height() + 40);

  });

  });

  -->

  </script>

  这里的find("#content")是找出iframe内容文档中的id为content的高度(另外比如find("body")),并设置给iframe,

  类似的还可以设置宽度,留给需要的朋友尝试吧。

  这样就解决了iframe不会因为内容过大被挡住的问题(因为我设置了scrolling="no")。

  PS:基本上我会优先考虑使用iframe来实现无刷新,兼容浏览器的后退按钮;而且使用iframe加载flash是很爽的,不用写什么js调用,object标签,还符合W3C标准。

  2008年11月28日17:13:31 ,今天使用过程中根据实际情况进行了一下改良,代码如下:

  

复制代码 代码如下:

  <script type="text/javascript">

  <!--

  $(function(){

  $("#workArea").load(function(){

  var height = $(this).contents().find("#box").height() + 40;

  //这样给以一个最小高度

  $(this).height( height < 400 ? 400 : height );

  });

  });

  -->

  </script>

  另发现使用find("body")不太好使,高度不准确。