????? iframe的高度自适应问题可以说不是一个新鲜的了。大家都知道iframe的高度是不能自适应的,那么我们需要他自适应怎么办呢?最简单的办法就是利用js在iframe加载的时候读出内容的高度,然后动态改变iframe的高度。但是如果我们引用的页面是站外的,不在同一个域名下就会出现问题。
????? 因为js通常是不支持跨域访问的,所以在这时候用js就不能捕获到页面内容的高度了,也就不能做到自适应了。那么我们该怎么做呢?既然不能跨域访问,那么我们就想办法把他放置在同一个域内。
这里我们需要3个文件。a.html,b.html,c.html.
????? 其中a 是用来放置iframe的,b是被引用的页面,c是我们的一个跳板。
?
?
a.htnl
?
<!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=gb2312″ /> <title>frame</title> </head> <body> <iframe id=”iId” name=”iId” src=http://b.test.com/b.html frameborder=”0″ scrolling=”no” width=100%></iframe> </body> </html>
?
?
?
?
b.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=gb2312″ /> <title>frame</title> </head> <body> <script language=”javascript”> var urlC = “http://a.test.com/c.html“; document.write(“<iframe id=\”iframeC\” name=\”iframeC\” src=\”"+urlC+”\” frameborder=\”0\” height=\”0\”></iframe>”); hashH = document.body.scrollHeight; document.getElementById(“iframeC”).src=urlC+”#”+hashH; </script> </body> </html>
?
?
?
?
c.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=gb2312″ /> <title>frame</title> </head> <script language=”javascript”> var iObjaa = this.parent.parent.document.getElementById(‘iId’); iObjHaa = this.parent.parent.frames["iId"].frames["iframeC"].location.hash; iObjaa.style.height = iObjHaa.split(“#”)[1]+”px”; </script> <body> </body> </html>
?
?
?
我们把c和a放在一个域名下,b放在另外一个域名下。当b加载的时候会获取自己的内容高度,并把这个高度通过c传递到a域名下,a和c在一个域名下,所以c内的js就可以操作a内的iframe了。最终达到iframe跨域高度自适应的目的。
文章作者:IceSun
本文地址:http://www.iscss.tk/?p=78
版权所有 ? 转载时必须以链接形式注明作者和原始出处!
?
欢迎查看本人博客:www.java.hourb.com
?