固定的容器中iframe寬高100%撐滿容器,iframe超出部分出現滾動條,iframe高度有多少,容器高度就有多少,iframe 自適應高度里面內容
iframe高度自適應里面的內容怎么實現?
一、固定的容器中iframe寬高100%撐滿容器,iframe超出部分出現滾動條
<!DOCTYPE html>
<html> <head lang="en"> <meta charset="UTF-8"> <title>固定的容器中iframe寬高100%撐滿容器,iframe超出部分出現滾動條http://www.51xuediannao.com/html5/981.html</title> </head> <body> <div class="test" style="width: 100%;height: 500px;"> <iframe src="iframe.html" frameborder="none" scrolling="auto" style="width: 100%; height: 100%;"></iframe> </div> </body> </html>
二、iframe高度有多少,容器高度就有多少,iframe高度自適應里面的內容
<!DOCTYPE html>
<html> <head lang="en"> <meta charset="UTF-8"> <title>iframe高度有多少,容器高度就有多少http://www.51xuediannao.com/html5/981.html</title> <style> html,body{ padding: 0; margin: 0;} </style> </head> <body> <div class="test" id="test" style="width: 100%;"> <iframe name="ifr" id="ifr" src="iframe.html" frameborder="none" scrolling="auto" style="width: 100%; height: 100%;"></iframe> </div> <script> function test(h){ document.getElementById("test").style.height = h+"px" } //在父級操作容器高度,這有個問題就是在iframe中的頁面有高度改變的時候這里並不會改變 /*document.getElementById("ifr").onload = function(){ document.getElementById("test").style.height = this.contentWindow.document.body.clientHeight+"px"; };*/ </script> </body> </html>
子iframe中的
js代碼
<!DOCTYPE html>
<html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> html,body,ol{ margin: 0; padding: 0;} li{ line-height: 30px;} li:nth-of-type(even){ background: #ddd;} </style> </head> <body> <div id="test">test</div> <div style="height: 2000px; background: #ddd;"></div> <script> function setHeight(){ var h = document.body.clientHeight; window.parent.test(h); } setHeight(); //頁面高度有改變的時候再次調用 setHeight 重置外層容器的高度http://www.51xuediannao.com/html5/981.html document.getElementById("test").onclick = function(){ this.style.height = "500px"; setHeight(); } </script> </body> </html>
還有其他辦法嗎?