我用iframe做了个编辑器,iframe里面有一个div设置为contentEditable="true"来实现的。现在希望编辑内容过长时,iframe会像div那样自动将高度变大,而不是出现滚动条,该怎样实现?网上搜索iframe高度自适应的一般是在iframe的onload中设置它的高度,但这只是在iframe加载内容时才有效,我要的是编辑内容变长时iframe也能改变高度。现在我通过在iframe里面的div的onresize事件中更改iframe的高度,但在firefox下失效。
调试欢乐多
<head>
<title>iframe自适应高度</title>
</head>
<body>
<div><iframe src="b.htm" onmouseover="test()"></iframe></div>
</body>
</html>
b.htm<html>
<head>
<title> </title>
<script type="text/javascript">
//自动调整iframe框架的方法
function iframeAuto()
{
try
{
if(window!=parent)
{
//定位需要调整的frame框架(在父级窗口中查找)
var a = parent.document.getElementsByTagName("IFRAME");
for(var i=0; i<a.length; i++)
{
if(a[i].contentWindow==window)
{
var h1=0, h2=0;
a[i].parentNode.style.height = a[i].offsetHeight +"px";
a[i].style.height = "10px"; //首先设置高度为10px,后面会修改
if(document.documentElement&&document.documentElement.scrollHeight)
{
h1=document.documentElement.scrollHeight;
}
if(document.body) h2=document.body.scrollHeight;
var h=Math.max(h1, h2); //取两者中的最大值
if(document.all) {h += 4;}
if(window.opera) {h += 1;}
//调整框架的大小
a[i].style.height = a[i].parentNode.style.height = h +"px";
} } }
}
catch (ex){}
}
//事件绑定的方法,支持IE5以上版本
if(window.attachEvent)
{
window.attachEvent("onload", iframeAuto);
}
else if(window.addEventListener)
{
window.addEventListener('load', iframeAuto, false);
}
//-->
</script>
</head>
<body>
<table border="1" width="200" style="height: 400px; background-color: gray">
<tr>
<td>iframe 自适应其加载的网页</td>
</tr>
</table>
</body>
</html> [/code]
试试看 兼容ie和firefox
代码简洁,速度快。
但要请教如何应用在不同Host之间。比如我的Ifram在A网站,而Src="在B网站" 我试过Resize无效,可以请教请教?敬请高人指点:[email protected]有空请来看小弟献丑:http://gogoyo.com谢谢!