方法一:JS動態修改iframe高度和寬度的方法
<!DOCTYPE html> <html> <head> <script> function changeSize() { document.getElementById("myframe").height="300"; document.getElementById("myframe").width="300"; } </script> </head> <body> <iframe id="myframe" src="/default.asp" height="200" width="200"> <p>Your browser does not support iframes.</p> </iframe> <br><br> <input type="button" onclick="changeSize()" value="Change size"> </body> </html>
方法二:iframe 去除邊框和自適應高度
因為做項目經常要用到頁面鑲嵌,每次都忘記一些細節問題,特地寫下來以便查閱,很久以前是網上搜到一些前輩的,但是時間太久忘記是哪位了,沒辦法給具體鏈接。
以下是js代碼:
<script type="text/javascript"> function reinitIframe() { var iframe = document.getElementById("frame"); try { var bHeight = iframe.contentWindow.document.body.scrollHeight; var dHeight = iframe.contentWindow.document.documentElement.scrollHeight; var height = Math.max(bHeight, dHeight); iframe.height = height; } catch (ex) {} } window.setInterval("reinitIframe()", 200); </script>
方法三:js控制iframe的高度/寬度,自適應內容
頁面使用方法: <iframe name="ifr_show" id="ifr_show" src="#" marginwidth="0" marginheight="0" frameborder="0" scrolling="no" width="100%" onload="IFrameReSize('ifr_show');"></iframe> JS: <script language="javascript" type="text/javascript"> function IFrameReSize(iframename) { var pTar = document.getElementByIdx_x(iframename); if (pTar) { //iframe高度自適應 if (pTar.contentDocument && pTar.contentDocument.body.offsetHeight) { pTar.height = pTar.contentDocument.body.offsetHeight; }else if (pTar.Document && pTar.Document.body.scrollHeight) { pTar.height = pTar.Document.body.scrollHeight; } //iframe寬度自適應 if (pTar.contentDocument && pTar.contentDocument.body.offsetWidth) { pTar.width = pTar.contentDocument.body.offsetWidth; }else if (pTar.Document && pTar.Document.body.scrollWidth) { pTar.width = pTar.Document.body.scrollWidth; } } } </script>
方法四:html5移動端引入優酷視頻iframe自適應
<iframe height=498 width=510 src="http://player.youku.com/embed/XMTI4MjU5OTA3Mg==" frameborder=0 allowfullscreen></iframe>
css里設置iframe的寬度為100%
根據屏幕寬度自適應,這里我設定視頻16/9的固定比例
window.onload = window.onresize = function () { resizeIframe(); } var resizeIframe=function(){ var bodyw=document.body.clientWidth; for(var ilength=0;ilength<=document.getElementsByTagName("iframe").length;ilength++){ document.getElementsByTagName("iframe")[ilength].height = bodyw*9/16;//設定高度 } }