随之而来的就是在实际使用iframe中,会遇到iframe高度的问题,由于被嵌套的页面长度不固定而显示出来的滚动条,不仅影响美观,还会对用户操作带来不便。于是自动调整iframe高度就成为本文的重点。
采用javascript来控制iframe元素的高度是iframe高度自适应的关键,同时由于javascript对不同域名下权限的控制,引发出同域、跨域两种情况。
1、同域时iframe高度自适应
下面的代码兼容IE/Firefox浏览器,控制id为"iframeid"的iframe的高度,通过JavaScript取得被嵌套页面最终高度,然后在主页面进行设置来实现。
代码如下,可复制。另外,请注意此解决方案仅供同域名下使用。
<script
type="text/javascript">
function setWinHeight(){
var iframeid = document.getElementById("iframeid");
if(document.getElementById){
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="setWinHeight()" height="1" frameborder="0"
src="test.html"></iframe>
2、跨域时iframe高度自适应
在主页面和被嵌套的iframe为不同域名的时候,就稍微麻烦一些,需要避开javascript的跨域限制。
原理:现有主页面main.html、main.html页面中iframe嵌套另一个页面iframe.html、iframe.html页面中的iframe嵌套agent.html中转页面,当用户浏览时执行iframe.html中的javascript代码设置获取agent页面的高度,(其中main.html和agent.html同域,iframe.html另一个域)在main.html的js设置iframe的高度。
代码结构:
1、当前域的主页面main.html
<!doctype
html>
<html>
<head>
<title>main主页面</title>
<style type="text/css">
.content{
border:1px solid #cccccc;
padding: 10px;
}
</style>
</head>
<body>
<div class="content">
<iframe id="frame_content" name="frame_content"
src="http://www.xxx.com/iframe.html" width="100%" height="0" scrolling="no"
frameborder="0">
</frame>
</div>
<div class="footer">页面底部</div>
</body>
</html>
2、跨域的iframe.html
<!doctype
html>
<html>
<head>
<title>iframe内容页面</title>
<style type="text/css">
.iframe_content{
height:3000px;
color:#ffffff;
background:#ffff00;
}
.hide{
display: none;
}
</style>
</head>
<body>
<div class="iframe_content">
iframe内容
</div>
<iframe id="iframe_agent" name="iframe_agent" src="" width="0" height="0"
class="hide">
</iframe>
<script type="text/javascript">
function setHash(){
hashHeight = document.documentElement.scrollHeight;
url = "http://www.xxx.com/agent.html"
document.getElementById("iframe_agent").src = url + "#" +
hashHeight;
}
window.onload = setHash();
</script>
</body>
</html>
3、当前域中转页面agent.html
<!doctype
html>
<html>
<head>
<title>iframe中转页面</title>
</head>
<body>
<script type="text/javascript">
function pageSetHeight(){
var rootIframe = parent.parent.document.getElementById("frame_content");
var agentHash =
parent.parent.frames["frame_content"].frames["frame_agent"].location.hash;
rootIframe.style.height = agentHash.split("#")[0] + "px";
}
pageSetHeight();
</script>
</body>
</html>
注意:
1、main.html的iframe的src地址需要为跨域的域名地址
2、iframe.html的iframe的src地址为当前域的中转页面地址