- <!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=utf-8" />
- <title>iframe自动适应高度</title>
- <script type="text/javascript">
- <!--//
- function sizeFrame() {
- var F = document.getElementById("myFrame");
- if(F.contentDocument) {
- F.height = F.contentDocument.documentElement.scrollHeight; //FF 3.0.11, Opera 9.63, and Chrome
- } else {
- F.height = F.contentWindow.document.body.scrollHeight; //IE6, IE7 and Chrome
- }
- }
- window.onload=sizeFrame;
- //-->
- </script>
- </head>
- <body>
- <iframe width="100%" id="myFrame" src="http://www.a.com" scrolling="no" frameborder="0">同域情况</iframe>
- </body>
- </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>
- <script type="text/javascript">
- <!--//
- function sizeFrame() {
- var F = document.getElementById("iframeB");
- if(F.contentDocument) {
- F.height = F.contentDocument.documentElement.scrollHeight; //FF 3.0.11, Opera 9.63, and Chrome
- } else {
- F.height = F.contentWindow.document.body.scrollHeight; //IE6, IE7 and Chrome
- }
- }
- window.onload=sizeFrame;
- //-->
- </script>
- </head>
- <body>
- <iframe id="iframeB" name="iframeB" src="http://www.b.com/test.html" width="100%" height="auto" scrolling="no" frameborder="0"></iframe>
- </body>
- </html>
- <iframe id="iframeA" name="iframeA" src="" width="0" height="0" style="display:none;" ></iframe>
- <script type="text/javascript">
- function sethash(){
- hashH = document.documentElement.scrollHeight; //获取自身高度
- urlC = "http://www.a.com/z.html"; //设置iframeA的src
- document.getElementById("iframeA").src=urlC+"#"+hashH; //将高度作为参数传递
- }
- window.onload=sethash;
- </script>
- <!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>
- <script type="text/javascript">
- function pseth() {
- var iObj = parent.parent.document.getElementById('iframeB');//A和main同域,所以可以访问节点
- iObjH = parent.parent.frames["iframeB"].frames["iframeA"].location.hash;//访问自己的location对象获取hash值
- iObj.style.height = iObjH.split("#")[1]+"px";//操作dom
- }
- pseth();
- </script>
- </head>
- <body>
- </body>
- </html>
转载:http://www.cnf2e.com/javascript/iframe-auto-height.html