在实际的项目进行中,很多地方可能由于历史原因不得不去使用iframe,包括目前正火热的应用开发也是如此。
随之而来的就是在实际使用iframe中,会遇到iframe高度的问题,由于被嵌套的页面长度不固定而显示出来的滚动条,不仅影响美观,还会对用户操作带来不便。于是自动调整iframe的高度就成为本文的重点。
采用javascript来控制iframe元素的高度是iframe高度自适应的关键,同时由于javascript对不同域名下权限的控制,引发出同域、跨域两种情况。
同域时iframe高度自适应
下面的代码兼容ie/firefox浏览器,控制id为“iframeid”的iframe的高度,通过javascript取得被嵌套页面最终高度,然后在主页面进行设置来实现。
项目结构:
其中iframe.html和main.html在同一个域下
代码如下,可复制。另外,请注意此解决方案仅供同域名下使用。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
function setcwinheight() {
var iframeid = document.getelementbyid("iframeid"); //iframe id
if(document.getelementbyid) {
if(iframeid && !window.opera) {
if(iframeid.contentdocument && iframeid.contentdocument.body.offsetheight) {
iframeid.height = iframeid.contentdocument.body.offsetheight;
} else if(iframeid.document && iframeid.document.body.scrollheight) {
iframeid.height = iframeid.document.body.scrollheight;
}
}
}
}
</script>
<iframe width="100%" id="iframeid" onload="javascript:setcwinheight()" height="1" frameborder="0" src="iframe.html"></iframe>
</body>
</html>
预览效果如下:
跨域时iframe高度自适应
在主页面和被嵌套的iframe为不同域名的时候,就稍微麻烦一些,需要避开javascript的跨域限制。
项目结构如下:
被嵌套的页面在另外一个tomcat下:
iframe主页面main.html
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>iframe主页面</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body>
<div style="border:1px solid #ccc;padding:10px;">
<iframe id="frame_content" name="frame_content" src="http://127.0.0.1:8080/tpl/iframe.html" width="100%" height="0" scrolling="no" frameborder="0"></iframe>
</div>
<br/>测试一下<br/>
</body>
代理页面agent.html
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<title>代理页面</title>
<script>
function pseth() {
var iobj = parent.parent.document.getelementbyid('frame_content');
iobjh = parent.parent.frames["frame_content"].frames["iframec"].location.hash;
iobj.style.height = iobjh.split("#")[1]+"px";
}
pseth();
</script>
被嵌套的页面iframe.html
<title>被iframe嵌套页面</title>
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<iframe id="iframec" name="iframec" src="" width="0" height="0" style="display:none;" ></iframe>
<script type="text/javascript">
function sethash(){
hashh = document.documentelement.scrollheight;
urlc = "http://127.0.0.1:8020/iframe3/agent.html";
document.getelementbyid("iframec").src=urlc+"#"+hashh;
window.onload=sethash;
最终预览效果: