2个文件放到同一个目录下,chrome访问需要通过web服务器,如tomcat ,127.0.0.1:8080/test/html/iframeParent.html。
1iframe.html
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<body>
<div id="initContent" onclick="addContent()">iframe里的内容</div>
</body>
<script type="text/javascript">
document.body.onload = new function(){
resetIframeHeight();
};
function resetIframeHeight() {
//获取iframe带滚动条时候的高度
var h = document.body.scrollHeight;
//对iframe(window.frameElement)设置高度,也可以通过id获取元素。
//chrome访问window.frameElement为null,在web服务器下访问可以正常。
//原因Chrome不允许采用file:协议引用父窗口。
window.frameElement.height = h;
}
function addContent(){
var initNode=document.getElementById("initContent");
var newNode = document.createElement("p");
newNode.innerHTML = "This is a p element";
initNode.parentNode.appendChild(newNode);
//initNode.parentNode.insertBefore(newNode,null);
resetIframeHeight();
}
</script>
父页面:iframeParent.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>iframe自适应高度demo</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body >
<div>父页面上</div>
<div>
<iframe name="picUpload" height="1px" width=100% frameborder=0 scrolling=no src="iframe.html">
</iframe>
</div>
<div>父页面下</div>
</body>
</html>
注意:chrome如果不通过web容器访问,报错:
Unsafe JavaScript attempt to access frame with URL file:///D:/mmt/workspace/thrillerzwtest/Web/html/iframeParent.html from frame with URL file:///D:/mmt/workspace/thrillerzwtest/Web/html/iframe.html. Domains, protocols and ports must match.
iframe.html:16
扩展:
iframe调用父窗口函数:
parent.resetIframeHeight();(或window.parent.resetIframeHeight();
父窗口调用iframe 的scrollHeight:
var picUpload=document.getElementById("picUpload");
var h = window.frames["picUpload"].document.body.scrollHeight;
// var h = picUpload.document.body.scrollHeight; //Uncaught TypeError: Cannot read property 'body' of undefined
picUpload.height = h;
appendChild() 方法在节点的子节点列表末添加新的子节点。pElement.appendChild(newNode);
insertBefore() 方法在节点的子节点列表任意位置插入新的节点。如:pElement.insertBefore (newNode,pElement.childNodes[0]);