您的位置:首页 > 其它

iframe高度自动适应

2008-09-22 13:05 405 查看
在Web开发过程中,为了提高页面架构层次的清晰性和灵活性,应对复杂的页面布局,使用嵌入式框架iframe可能是最有效的解决办法。如果布局比较复杂或页面层次较多,则可能会用到嵌套多层的iframe,然而iframe并不会根据页面高度自动调整自身高度,为了屏蔽滚动条提高视觉效果,就需要使用javascript代码使iframe自动调整高度。

1、单层情况,假设在A.aspx页面的某个位置嵌入页面B.aspx,则在A页面中需使用一个嵌入框架iframeA,其示例代码如下:


...


<head>


...


<script type="text/javascript">


//iframeName:框架ID


function SetIframeSize(iframeName)




...{


var iframe = document.getElementById(iframeName);


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)...{}


}


</script>


</head>


<body>


...


<tr>


<td>


<iframe id="iframeA" name="iframeA" scrolling="no" frameborder="0" src="B.aspx" width="100%"




onload="SetIframeSize('iframeA');"></iframe>


</td>


<tr>


...


</body>


...

2、嵌套两层情况,假设A.aspx页面通过嵌入式框架iframeA嵌入页面B.aspx,页面B.aspx又通过嵌入式框架iframeB嵌入页面C.aspx,其中A.aspx示例代码和单层情况一样,B.aspx页面的示例代码如下:


...


<head>


...


<script type="text/javascript">


//iParentFrameName:父框架ID


//iframeName:框架ID


function SetIframeSize(iParentFrameName,iframeName)




...{


var iframe = document.getElementById(iframeName);


try




...{


var bHeight = iframe.contentWindow.document.body.scrollHeight;


var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;


//据说这两个高度可能不一样


var height = Math.max(bHeight, dHeight);


iframe.height = height;


//更新父框架高度


SetIframeSize2(iParentFrameName)




}catch (ex)...{}


}




//iframeName:框架ID


function SetIframeSize2(iframeName)




...{


var iframe = window.parent.parent.document.getElementById(iframeName);


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)...{}


}


</script>


</head>


<body>


...


<tr>


<td>


<iframe id="iframeB" name="iframeB" scrolling="no" frameborder="0" src="C.aspx" width="100%"




onload="SetIframeSize('iframeA','iframeB');"></iframe>


</td>


<tr>


...


</body>


...

其中代码
var iframe = window.parent.parent.document.getElementById(iframeName);
window指C.aspx,window.parent指B.aspx,window.parent.parent指A.aspx
事实上如果没有特别需要(比如B.aspx页面条件加载C.aspx页面)下,A.aspx中iframeA可以不要onload事件。

3、嵌套多层情况
多层嵌层以两层情况为例类推,同上没有特别需要,只设最后一级iframe的onload事件。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: