<!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>
因为做项目经常要用到页面镶嵌,每次都忘记一些细节问题,特地写下来以便查阅,很久以前是网上搜到一些前辈的,但是时间太久忘记是哪位了,没办法给具体链接。
以下是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>
页面使用方法: <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>
<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;//设定高度 } }
Copyright © 广州京杭网络科技有限公司 2005-2024 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有