Chinaunix首页 | 论坛 | 博客
  • 博客访问: 811928
  • 博文数量: 62
  • 博客积分: 526
  • 博客等级: 二等列兵
  • 技术积分: 2078
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-04 20:41
个人简介

博客迁移至 freefe.cc

文章分类

全部博文(62)

分类: JavaScript

2014-09-09 11:10:33



    iframe 自适应高度,目前最广泛的实现方式是以 JS 获取 iframe 所载入页面的 body 高度。(在本地 html 文件测试的时候 chrome 会有跨域错误,可以使用 IE 来测试)。其实质就是通过 offsetHeight 或者 scrollHeight 获取到 iframe 内部 body 的高度,再调整 iframe 高度即可。以下是初略形式:

Test.html 源码
  1. <!DOCTYPE HTML>
  2. <html>
  3.   <head>
  4.     <title>iframe 自适应高度</title>
  5.     <meta charset="UTF-8"/>
  6.   </head>
  7.   <body>
  8.     <iframe id="auto" name="auto" src="./Test2.html" width="100%" onload="autoHeight()"></iframe>
  9.     <script type="text/javascript" charset="utf-8">
  10.       function autoHeight(){
  11.         var ifr = document.getElementById('auto');
  12.         ifr.height = ( ifr.contentDocument && ifr.contentDocument.body.offsetHeight ) ||
  13.                      ( ifr.contentWindow.document.body.scrollHeight );
  14.       }
  15.     </script>
  16.   </body>
  17. </html>

Test2.html 源码

  1. <!DOCTYPE HTML>
  2. <html>
  3.   <head>
  4.     <title>iframe 自适应高度</title>
  5.     <meta charset="UTF-8"/>
  6.     <style type="text/css">
  7.       html,body{
  8.         margin: 0;
  9.         padding: 0;
  10.       }
  11.       #block{
  12.         background-color: red;
  13.         height: 500px;
  14.         width: 800px;
  15.       }
  16.     </style>
  17.   </head>
  18.   <body>
  19.     <div id="block"> </div>
  20.   </body>
  21. </html>

当然以上只是简单的实现,具体更严谨的计算高度做好使用一些兼容性不错库作为基础。


原文作者:lovenyf
原文博客:lovenyf.blog.chinaunix.net

阅读(6726) | 评论(3) | 转发(1) |
给主人留下些什么吧!~~

lovenyf2014-09-15 11:16:50

xdsnet:一个问题是iframe调整高度的时机,如果刷新发生在内嵌页面还没加载完的时候,是不会有好效果的。

这个应该看需求来确定触发时间吧,如果对于触发情况要求较高的话,事件绑定加页面上setTimeout循环也是一个不错的选着

回复 | 举报

xdsnet2014-09-14 08:33:56

一个问题是iframe调整高度的时机,如果刷新发生在内嵌页面还没加载完的时候,是不会有好效果的。

usheweb2014-09-12 09:48:09

chrome 里面设置html body iframe以及iframe的父标签高度百分百就好了 我以前写的一篇博文 http://www.usheweb.com/a/boke/20140731/799.html