iframe跨域高度自适应的实现
主框架代码
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
</head>
<body>
支持跨域的框架高度自适应
<hr>
<iframe id="autoFrame" name="autoFrame" src="http://u.com/frame.html"
width="100%" height="0" scrolling="auto" onload="frameResize()" frameborder="0"></iframe>
<hr>
<script language='javascript'>
function frameResize() {
var frameName = 'autoFrame';
if(typeof(h) == 'undefined') {
h = 0;
}
if(h > 0) {
document.getElementById(frameName).style.height = h + 'px';
} else {
try
{
h = window.frames[frameName].frames['xclient'].location.hash.substring(1);
}
catch (e)
{
}
setTimeout(frameResize, 1);
}
}
</script>
</body>
</html>
子域的框架代码
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<script type="text/javascript">
function ForResize()
{
var h = document.documentElement.scrollHeight || document.body.scrollHeight;
if (document.getElementById('xclient'))
{
var divEl = document.getElementById('xclient').parentNode;
divEl.parentNode.removeChild(divEl);
}
var el = document.createElement('div');
el.innerHTML = '<iframe src="http://u.com/xclient.html# + h + '" name="xclient" id="xclient" width="0" height="0" style="display:none;"></iframe>';
document.body.appendChild(el);
}
</script>
</head>
<body onload="ForResize()">
这里是框架的内容, 自适应这里的高度, 支持跨域
<br>
asdfsdf<br>asdfsdf<br>asdfsdf<br>asdfsdf<br>
asdfsdf<br>asdfsdf<br>asdfsdf<br>asdfsdf
<br>asdfsdf<br>
asdfsdf<br>
asdfsdf
<br>
asdfsdf山高水低个的
</body>
</html>
同时在当前域的根目录增加xclient.html文件,内容为空即可, 避免返回404错误