度自适应的实现方法有不少了,今天我们以css iframe高度自适应示例来为各位引起一些js与jquery的例子,有兴趣的可以和小编一起来看看。
前因:某个项目为了统计效果,把咨询的页面窗口内嵌放进一个单独的空页面,在这个页面里加了个统计,让人看着这个页面就跟直接进入咨询页面一样,懒得折腾啥js,直接用css弄了下,还好需求也不太高。OK了吧。
后果:因为接触iframe很少,几乎就没用过,所以当时就谷歌、百度了下,也不记得当时都搜到了些啥个内容,反正需求也不太强,就直接用css解决了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>页面内嵌iframe设置宽高度为100% | 格桑的blog</title> <style type="text/css"> html, body, table, tbody, tr, td { width:100%; height:100%; overflow:hidden;} iframe { width:100%; height:100%; border:none;} table{ border-colla<a href="/fw/photo.html" target="_blank">ps</a>e:collapse; border} </style> </head> <body style="margin:0; padding:0;"> <table cellpadding="0" cellspacing="0"> <tbody> <tr> <td> <iframe src="http://www.cn.net/" frameborder="0" marginwidth="0" marginheight="0"></iframe> </td> </tr> </tbody> </table> </body> </html> |
目测貌似把table去掉也是可以滴,没有测试过的哦。
下面的两种方法自选其一就行了。一个是放在和iframe同页面的,一个是放在test.html页面的。
注意别放错地方了哦。
iframe代码,注意要写ID
1 2 3 4 5 6 7 8 | <iframe src="test.html" id="main" width="700" height="300" frameborder="0" scrolling="auto"></iframe> jquery代码1: //注意:下面的代码是放在test.html调用 $(window.parent.document).find("#main").load(function(){ var main = $(window.parent.document).find("#main"); var thisheight = $(document).height()+30; main.height(thisheight); }); |
jquery代码2:
1 2 3 4 5 6 7 8 9 | //注意:下面的代码是放在和iframe同一个页面调用 $("#main").load(function(){ var mainheight = $(this).contents().find("body").height()+30; $(this).height(mainheight); }); |
HTML代码:
1 2 3 4 5 6 7 8 9 10 11 | <iframe src="http://www.cn.net/" id="iframepage" name="iframepage" frameBorder=0 scrolling=no width="100%" onLoad="iFrameHeight()" ></iframe> Javascript代码: <script type="text/<a href="/js_a/js.html" target="_blank">javascript</a>" language="javascript"> function iFrameHeight() { 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>
|