代码描述:iframe 跨域高度自适应。iframe 跨域高度自适应
在实际应用中,很多时候通过
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.51qianduan.com/" /> <title>iframe 跨域高度自适应</title> <script type="text/javascript"> window.onload=function(){ var ifm= document.getElementById("iframepage"); var subWeb = document.frames ? document.frames["iframepage"].document:ifm.contentDocument; if(ifm != null && subWeb != null){ ifm.height = subWeb.body.scrollHeight; } } </script> </head> <body> <iframe src="iframe.html" id="iframepage" name="iframepage" width="100%"></iframe> </body> </html>
以上代码可以实现我们的要求,但是很多时候通过iframe引入的页面是跨域的,上面的代码就不起作用,这是因为在引入外部页面的过程中,由于跨域安全问题会导致报错。 因而会导致设置高度的代码无法得到执行,也就无从谈起高度自适应了,可以改变一下思路实现此功能。 我们可以通过一个“中介”来完成此任务。 比如在域A中有一个页面a.html,我们要引入域C中的页面c.html,这样我们可以在域A中再建立一个“中介”页面b.html,作为c.html的子页面,然后获取一些相关信息,最后通过b.html来实现设置a.html中iframe高度的效果,因为b和a是在同域下的,所以不存在安全障碍。 c.html中的代码如下:
<script> <iframe id="b_id" width="100%" src="http://域A/b.html" style="display:none"> </iframe> <script type="text/javascript"> var c_height=Math.max(document.body.scrollHeight,document.body.clientHeight); var b_iframe = document.getElementById("b_id"); b_iframe.src = b_frame.src+"#"+b_height; </script>
通过url,为"中介"页面b.html传递了c.html的高度信息,这个高度就是a.html中iframe的自适应高度。 b.html中的代码如下:
//得到a.html中的a_iframe var a_iframe=parent.parent.document.getElementById("a_iframe"); var hash_url = window.location.hash; //得到传递过来的height属性 var hash_height = hash_url.split("#")[1]+"px"; //调整a_iframe的height,达到自适应 a_iframe.height = hash_height;
综上所述,就可以实现跨域iframe高度自适应效果了。
请绑定手机号,在继续操作
注意:只有绑定手机以后,才可使用网站全部功能