iframe自适应高度传统做法大致有两个:
方法一,在每个被包含页在本身内容加载完毕之后,执行JS取得本页面的高度,然后去同步父页面的iframe高度。
方法二,在主页面iframe的onload事件中执行JS,去取得被包含页的高度内容,然后去同步高度。
在代码维护角度考虑,方法二是优于方法一的,因为方法一,每个被包含页都要去引入一段相同的代码来做这个事情,创建了好多副本。
但是碰到有些页面会根据用户的操作或者为了增加用户体验的时候我们的页面高度可能会增加。这就要求使用其他办法:我们可以用setInterval();
代码如下:
XML/HTML代码
- <!DOCTYPE?html?PUBLIC?”-//W3C//DTD?XHTML?1.0?Transitional//EN”?”https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>??
- <html?xmlns=“https://www.w3.org/1999/xhtml”><HEAD><TITLE>iframe自适应高度-demo</TITLE>??
- <META?http-equiv=Content-Type?content=“text/html;?charset=GBK”>??
- <META?content=“MSHTML?6.00.6001.18063”?name=GENERATOR></HEAD>??
- <BODY>??
- <DIV? ??
- style=“BORDER-RIGHT:?1px?dotted;?BORDER-TOP:?1px?dotted;?BORDER-LEFT:?1px?dotted;?WIDTH:?400px;?BORDER-BOTTOM:?1px?dotted”><IFRAME? ??
- id=frame_content?src=“iframe_b.html”?frameBorder=0?scrolling=no? ??
- onload=this.height=100></IFRAME></DIV>??
- <DIV><BUTTON?onclick=checkHeight()>Check?Height</BUTTON></DIV>??
- <SCRIPT?type=text/javascript>??
- ????????????function?reinitIframe(){ ??
- ????????????????var?iframe?=?document.getElementById(“frame_content”); ??
- ????????????????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); ??
- ???????????? ??
- ????????????function?checkHeight()?{ ??
- ????????????????var?iframe?=?document.getElementById(“frame_content”); ??
- ????????????????var?bHeight?=?iframe.contentWindow.document.body.scrollHeight; ??
- ????????????????var?dHeight?=?iframe.contentWindow.document.documentElement.scrollHeight; ??
- ????????????????alert(“bHeight:”?+?bHeight?+?”,?dHeight:”?+?dHeight); ??
- ????????????} ??
- ????????</SCRIPT>??
- </BODY></HTML>??
最新评论
写的挺好的
有没有兴趣翻译 impatient js? https://exploringjs.com/impatient-js/index.html
Flexbox playground is so great!
感谢总结。
awesome!
这个好像很早就看到类似的文章了
比其他的教程好太多了
柯理化讲的好模糊…没懂