您的位置:首页 > 其它

iframe的几个常见问题

2016-12-26 15:52 393 查看
iframe的几个常见问题

 1.iframe的透明问题

除了IE家族,其他标准浏览器默认iframe是透明的。

对应IE7+ 的浏览器:

加个allowtransparency="true"如下

 
<!DOCTYPE HTML> 
<html> 
<head> 
<title>无标题</title> 
</head> 
<body style="background-color:#ccc;"> 
<iframe allowtransparency="true" src="ifrm.html"></iframe> 
</body> 
</html> 

对应ie6还要设置iframe页面的body背景透明

 
<!DOCTYPE HTML> 
<html> 
<head> 
<title>内框架页</title> 
</head> 
<body style="background-color:transparent;"> 
这里是内框架页面。 
</body> 
</html> 

注:如果iframe页面不在同一域下,发现此方法失效。

2.去边框,滚动条等

 边框:

除了ie家族,可以使用css的border:none;实现。

ie得需设置iframe的frameborder="no"或者frameborder="0"实现,于是兼容的写法如下:

 
<iframe allowtransparency="true" src="ifrm.html" style="border:none;" frameborder="no"></iframe> 

滚动条:

隐藏滚动条可以用scrolling="no"(此方式兼容所有的浏览器)
<iframe allowtransparency="true" src="ifrm.html" scrolling="no" style="border:none;" frameborder="no"></iframe> 

 

对于ie8,ff3,chrome等,设置框架页的body的overflow:hidden;也可以隐藏滚动条(ie6,7,或者iframe页面对你不可控时不行)。

3.iframe自适应宽高度

 注:iframe的默认尺寸是300*150px

 方法是在iframe文档的onload加载句柄里做



 
<iframe id="myifrm" onload="this.height=myifrm.document.body.scrollHeight;" allowtransparency="true" src="ifrm.html" scrolling="no" style="border:none;" frameborder="no"></iframe> 

 就把iframe里的页面的高度赋值给iframe框架窗口高度。

但这个火狐,认name窗口名,不信可以把id改成name试试,所以,兼容的写法是同时加上name,如:

 
<!DOCTYPE HTML> 
<html> 
<head> 
<title>无标题</title> 
</head> 
<body style="background-color:#ccc;"> 
<iframe id="myifrm" name="myifrm" onload="this.height=myifrm.document.body.scrollHeight;" allowtransparency="true" src="ifrm.html" scrolling="no" style="border:none;" frameborder="no"></iframe> 
</body> 
</html> 

或者不写name也行(ie6,7未测试):

 
<!DOCTYPE HTML> 
<html> 
<head> 
<title>无标题</title> 
</head> 
<body style="background-color:#ccc;"> 
<iframe id="myifrm" onload="this.height=document.getElementById('myifrm').contentDocument.body.scrollHeight;" allowtransparency="true" src="ifrm.html" scrolling="no" style="border:none;" frameborder="no"></iframe> 
</body> 
</html> 

 

这里再提供一个网上写好的一个函数:

 
<!DOCTYPE HTML> 
<html> 
<head> 
<title>无标题</title> 
<script type="text/javascript" language="javascript">    
function iFrameHeight() {    
    var ifm= document.getElementById("myifrm");    
    var subWeb = document.frames ? document.frames["myifrm"].document : ifm.contentDocument;    
    if(ifm != null && subWeb != null) { 
       ifm.height = subWeb.body.scrollHeight; 
    }    
}    
</script> 
</head> 
<body style="background-color:#ccc;"> 
<iframe id="myifrm" onload="iFrameHeight();" allowtransparency="true" src="ifrm.html" scrolling="no" style="border:none;" frameborder="no"></iframe> 
</body> 
</html> 

 

注意:这里在chrome里,通过file://访问发现不行,但是http://可以,不知道何故。

 

在onload里处理有个问题,就是无法应对ifrm页面里内容变动引起高度变化,简单说,比如tab页签,2个tab页高度不一样,切换时就有问题了。

在口碑UED博客看到,通过定时执行一下的方法:

 
window.setInterval("iFrameHeight()", 200); 

4.iframe页面与包含窗口的互通信 

5.连带父子页面刷新问题
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息