为什么需要使用iframe自适应高度呢?其实就是为了美观,要不然iframe和窗口长短大小不一,看起来总是不那么舒服,特别是对于我们这些编程的来说,如鲠在喉的感觉。在页面中通过iframe嵌入了另外一个页面后,如何使得页面的这块区域随着iframe的高度自动适应而不会出现蹩脚的上下左右滚动条呢?下面这个办法就是使用javascript实现iframe高度自适应的,这个可是兼容所有浏览器的,ie,firefox,chrome,opera,safari这些浏览器都能够实现iframe高度自适应的,具体的js代码如下:
function dyniframesize(down){
var sys={};
var ua=navigator.useragent.tolowercase();
var s;
(s=ua.match(/msie ([\d.]+)/))?sys.ie=s[1]:
(s=ua.match(/firefox\/([\d.]+)/))?sys.firefox=s[1]:
(s=ua.match(/chrome\/([\d.]+)/))?sys.chrome=s[1]:
(s=ua.match(/opera.([\d.]+)/))?sys.opera=s[1]:
(s=ua.match(/version\/([\d.]+).*safari/))?sys.safari=s[1]:0;
var ptar=null;
if (document.getelementbyid){
ptar=document.getelementbyid(down);
}else{
eval('ptar='+down+';');
}
ptar.style.display="block";
if (sys.ie){
if(sys.ie=='9.0'){
ptar.height=ptar.contentwindow.document.body.offsetheight+15+"px";
ptar.width=ptar.contentwindow.document.body.scrollwidth+"px";
}else if(sys.ie=='8.0'){
ptar.height=ptar.document.body.offsetheight+15+"px";
ptar.width=ptar.document.body.scrollwidth+"px";
}else{
ptar.height=ptar.document.body.scrollheight+25+"px";
ptar.width=ptar.document.body.scrollwidth+"px";
}
}
if (sys.firefox){
ptar.height=ptar.contentdocument.body.offsetheight+15+"px";
ptar.width=ptar.contentdocument.body.scrollwidth+"px";
}
if (sys.chrome){
ptar.height=ptar.contentdocument.body.offsetheight;
ptar.width=ptar.contentdocument.body.scrollwidth;
}
if (sys.opera){
ptar.height=ptar.contentdocument.body.offsetheight;
ptar.width=ptar.contentdocument.body.scrollwidth;
}
if (sys.safari){
if(ptar.contentdocument.body.offsetheight <= '186'){
ptar.height=ptar.contentdocument.body.offsetheight+10;
}else{
ptar.height=ptar.contentdocument.body.offsetheight;
}
ptar.width=ptar.contentdocument.body.scrollwidth;
}
}
具体的使用方法如下(设置id=phpernote的iframe的高度自适应iframe里面的内容高度):
<iframe marginwidth="0" framespacing="0" marginheight="0" frameborder="0" border="0" width="620px"
style="border:0px;background:#fff;max-height:245px;
" scrolling="no" src="http://www.phpernote.com/comm/page/218167" id="phpernote" onload="javascript:dyniframesize('phpernote');">
</iframe>
上篇文章我们介绍了如何使用iframe属性,这篇文章也依然教大家iframe自适应高度的解决办法,希望两篇文章让你对iframe标签有一个更深入的了解。
相关推荐:
如何使用iframe属性
php中关于main与 iframe相互通讯类详解
php表单文件iframe异步上传教程讲解
分享iframe标签注意问题
html iframe使用的实战总结分享
以上就是让iframe自适应高度的讲解的详细内容。