度自適應的實現方法有不少了,今天我們以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>
|