当前位置: 首页 > 图文教程 > 网页制作 > HTML/XHTML教程 > iframe自适应大小

HTML/XHTML教程
HTML5之后W3C将制定无版本号的HTML
IE6必然灭亡的最新6个理由
网页制作教程:单独对IE6进行兼容
Firefox 3.6频繁崩溃的问题
HTML5的发展:微格式和相关的属性名称
Chrome最新4.0版本支持GreaseMonkey脚本
网页前端常见的攻击方式和预防攻击办法
HTML5标准将把互联网视频扔回到黑暗时代
靠我们自己的力量把IE6推向灭亡
近期热点:HTML5是否真的可以取代Flash
网页知识新手了解:网页设计的发展历史
TinyEditor:简洁且易用的html所见即所得编辑器
ANSI,Unicode,UTF-8网页编码的区别
HTML5实例:20个使用HTML5编写的网站
网页表单设计:主要行为与次要行为
HTML网页实例代码:简洁漂亮的跳转等待页面
经验分享:关于网页布局排版的流程问题
W3C发布7个HTML工作草案
HTML5 旨在解决 Web 中的交互
网页优化的最基础部分:HTML的优化

HTML/XHTML教程 中的 iframe自适应大小


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 57 ::
收藏到网摘: n/a

页面域关系

主页面a.html所属域A:www.taobao.com
被iframe的页面b.html所属域B:www.alimama.com,假设地址:http://www.alimama.com/b.html

实现效果

A域名下的页面a.html中通过iframe嵌入B域名下的页面b.html,由于b.html的宽度和高度是不可预知而且会变化的,所以需要a.html中的iframe自适应大小.

问题本质:

js对跨域iframe访问问题,因为要控制a.html中iframe的高度和宽度就必须首先读取得到b.html的大小,A、B不属于同一个域,浏览器为了安全性考虑,使js跨域访问受限,读取不到b.html的高度和宽度.

解决方案:

引入代理代理页面c.html与a.html所属相同域A,c.html是A域下提供好的中间代理页面,假设c.html的地址:www.taobao.com/c.html,它负责读取location.hash里面的width和height的值,然后设置与它同域下的a.html中的iframe的宽度和高度.

代码如下:

a.html代码

首先a.html中通过iframe引入了b.html
<iframe id=”b_iframe” height=”0″ width=”0″ src=”http://www.alimama.com/b.html” frameborder=”no” border=”0px” marginwidth=”0″ marginheight=”0″ scrolling=”no” allowtransparency=”yes” ></iframe>

b.html代码

<script type=”text/javascript”>
  var b_width = Math.max(document.documentElement.clientWidth,document.body.clientWidth);
  var b_height = Math.max(document.documentElement.clientHeight,document.body.clientHeight);
  var c_iframe = document.getElementById(”c_iframe”);
  c_iframe.src = c_iframe.src+”#”+b_width+”|”+b_height; //http://www.taobao.com/c.html#width|height”
}
</script>
<!–js读取b.html的宽和高,把读取到的宽和高设置到和a.html在同一个域的中间代理页面车c.html的src的hash里面–>
<iframe id=”c_iframe”  height=”0″ width=”0″  src=”http://www.taobao.com/c.html” style=”display:none” ></iframe>

c.html代码

<script type=”text/javascript”>
var b_iframe = parent.parent.document.getElementById(”b_iframe”);
var hash_url = window.location.hash;
var hash_width = hash_url.split(”#”)[1].split(”|”)[0]+”px”;
var hash_height = hash_url.split(”#”)[1].split(”|”)[1]+”px”;
b_iframe.style.width = hash_width;
b_iframe.style.height = hash_height;
</script>
a.html中的iframe就可以自适应为b.html的宽和高了.

其他一些类似js跨域操作问题也可以按这个思路去解决