iframe高度自适应
1 父页面设置脚本(脚本必须在下):
父页:
1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 5 <script src="../js/jquery-1.10.2.js"></script> 6 <title></title> 7 </head> 8 <body> 9 <iframe id="ifr" src="iframe.html" frameborder="0" width="100%"></iframe> 10 <script type="text/javascript"> 11 // 计算页面的实际高度,iframe自适应会用到 12 function calcPageHeight(doc) { 13 var cHeight = Math.max(doc.body.clientHeight, doc.documentElement.clientHeight) 14 var sHeight = Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight) 15 var height = Math.max(cHeight, sHeight) 16 return height 17 } 18 19 var ifr = document.getElementById('ifr') 20 ifr.onload = function () { 21 var iDoc = ifr.contentDocument || ifr.document 22 var height = calcPageHeight(iDoc) 23 ifr.style.height = height + 'px' 24 } 25 </script> 26 </body> 27 </html>
子页:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 </head> 6 <body> 7 <p>这是一个ifrmae,嵌入在http://snandy.github.io/lib/iframe/1.html里 </p> 8 <p>根据自身内容调整高度</p> 9 <p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p> 10 </body> 11 </html>
2 子页面设置脚本:
父页:
1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 5 <script src="../js/jquery-1.10.2.js"></script> 6 <title></title> 7 </head> 8 <body> 9 <iframe id="ifr" src="iframe.html" frameborder="0" width="100%"></iframe> 10 </body> 11 </html>
子页:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>2.html</title> 6 <script> 7 // 计算页面的实际高度,iframe自适应会用到 8 function calcPageHeight(doc) { 9 var cHeight = Math.max(doc.body.clientHeight, doc.documentElement.clientHeight); 10 var sHeight = Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight); 11 var height = Math.max(cHeight, sHeight); 12 return height; 13 } 14 15 window.onload = function () { 16 var height = calcPageHeight(document); 17 parent.document.getElementById('ifr').style.height = height + 'px'; 18 } 19 </script> 20 </head> 21 <body> 22 <p>这是一个ifrmae,嵌入在http://snandy.github.io/lib/iframe/1.html里 </p> 23 <p>根据自身内容调整高度</p> 24 <p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p> 25 </body> 26 </html>
参考:http://www.cnblogs.com/snandy/p/3902337.html