2018-01-04 10:03:21
同域下的iframe自适应
同域下实现iframe自适应比较简单,可以直接利用javascript操作DOM来达到目的。下面的示例是在http://localhost:8887作用域下,iframe.html引入index.html。
index.html
| 
 1 
 | 
<img src="ghost.png" alt="ghost" style="width:600px; height: 300px;"> | 
iframe.html
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
 | 
<iframe id="iframe" src="index.html" frameborder="0"scrolling="no" style="border: 0px;"></iframe> <script>    // 兼容性代码  function autoHeight(iframe) {    if (iframe) {      var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;      if (iframeWin.document.body) {        iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;        iframe.width = iframeWin.document.documentElement.scrollWidth || iframeWin.document.body.scrollWidth;      }    }  }  window.onload = function() {    autoHeight(document.getElementById('iframe'));  }</script> | 
显示效果

注意:一定要通过服务器来访问iframe.html,像chrome这样的浏览器访问本地静态文件会有限制,导致错误!
跨域下的iframe自适应
跨域(只要协议、域名、端口有任何一个不同,都被当作是不同的域)的时候,由于js的同源策略,父页面内的js不能获取到iframe页面的大小。
解决方案原理:使用代理页面,并通过location.hash来进行传值。
示例如下:http://localhost:8887下的一个页面a.html使用iframe标签引入http://localhost:8888下的一个页面b.html。在http://localhost:8887下创建一个agent.html页面做代理,b.html此时可利用隐藏的iframe通过location.hash将自己的大小传给agent.html。由于agent.html与a.html在同一个域下,所以agent.html可直接操作a.html,不受js同源限制。
a.html
| 
 1 
2 
 | 
// 引入b.html<iframe id="a_iframe" src="http://localhost:8888/b.html"frameborder="0" scrolling="no" style="border: 0;"></iframe> | 
b.html
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
 | 
<img src="ghost.png" alt="ghost" style="width:600px; height: 300px;"> // 通过隐藏的iframe,利用loacation.hash传值<iframe id="b_iframe" src="http://localhost:8887/agent.html"height="0" width="0" frameborder="0" style="display: none;"></iframe> <script>  (function autoHeight() {    var width = Math.max(document.body.scrollWidth, document.body.clientWidth);    var height = Math.max(document.body.scrollHeight, document.body.clientHeight);    var b_iframe = document.getElementById("b_iframe");    b_iframe.src = b_iframe.src + "#" + width + "|" + height;  })();</script> | 
agent.html
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
 | 
<script>  var a_iframe = window.parent.parent.document.getElementById("a_iframe");  var hash_url = window.location.hash;  if (hash_url.indexOf("#") >= 0) {    var hash_width = hash_url.split("#")[1].split("|")[0] + "px";    var hash_height = hash_url.split("#")[1].split("|")[1] + "px";    a_iframe.style.width = hash_width;    a_iframe.style.height = hash_height;  }</script> | 
	更多精彩内容:各种AI课程、技能课程、黑科技软件、网站小程序源码、副业小项目、PPT模板等精品素材、电商课程、推广引流课程等,尽在 天边资源网 。