网上关于iframe高度自适应的代码有很多,但比较杂乱,本文根据实用性整理了以下代码:
JavaScript部分:
折叠JavaScript Code复制内容到剪贴板
<script type="text/javascript">
function SetCwinHeight(iframeObj){
if (document.getElementById){
if (iframeObj){
if (iframeObj.contentDocument && iframeObj.contentDocument.body.offsetHeight){
iframeObj.height = iframeObj.contentDocument.body.offsetHeight;
} else if (document.frames[iframeObj.name].document && document.frames[iframeObj.name].document.body.scrollHeight){ iframeObj.height = document.frames[iframeObj.name].document.body.scrollHeight;
}
}
}
}
</script>
html部分:
折叠XML/HTML Code复制内容到剪贴板
<iframe name="frameContent" src="*" frameborder="0" width="100%" onload="SetCwinHeight(this)"></iframe>
标记*号的地方填入iframe页面的地址。需要注意的是,src地址必须是在同一网站下,否则会出现“权限被禁止”的错误。