1.js在iframe子页面操作父页面元素代码:
window.parent.document.getElementById("父页面元素id");
2.js在父页面获取iframe子页面元素代码如下:
window.frames["iframe_ID"].document.getElementById("子页面元素id");
3.jquery在iframe子页面获取父页面元素代码如下 :
$("#objid",parent.document)
4.jquery在父页面获取iframe子页面的元素 jquery在父页面获取iframe子页面的元素
$("#objid",document.frames('iframename').document)
5.在iframe中调用父页面中定义的方法和变量:
window.parent.window.parentMethod();
window.parent.window.parentValue;
6.在父页面操作iframe子页面的方法和变量
window.frames["iframe_ID"].window.childMethod();
window.frames["iframe_ID"].window.childValue;
一:同域下父子页面交互
(1):父页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function say(){
alert("父级页面");
}
function callChild(){
myFrame.window.say();
myFrame.window.document.getElementById("button").value="子页面调用结束";
}
</script>
</head>
<body>
<input id="button" type="button" value="调用子页面中的函数say()" onclick="callChild()"/>
<iframe name="myFrame" src="child.html"></iframe>
</body>
</html>
(2):子页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function say(){
alert("子级页面");
}
function callParent(){
parent.say();
parent.window.document.getElementById("button").value="父页面调用结束";
}
</script>
</head>
<body>
<input id="button" type="button" value="调用父页面中的say()函数" onclick="callParent()"/>
</body>
</html>
注意:要确保在iframe加载完成后再进行操作,如果iframe还未加载完成就开始调用里面的方法或变量,会产生错误。
二:iframe高度自适应
这个时候,我们可以给它添加一个默认的CSS的min-height值,然后同时使用JavaScript改变高度。常用的兼容代码有:
function setIframeHeight(iframe) {
if (iframe) {
var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;
if (iframeWin.document.body) {
iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;
}
}
};
window.onload = function () {
setIframeHeight(document.getElementById('iframe的ID'));
};
注意:只要修改以上的iframe的ID即可了。
三:内容宽度变化的iframe高度自适应
<iframe src="backtop.html" frameborder="0" scrolling="no" id="test" "this.height=100"></iframe>
<script type="text/javascript">
function reinitIframe(){
var iframe = document.getElementById("test");
try{
var bHeight = iframe.contentWindow.document.body.scrollHeight;
var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
var height = Math.max(bHeight, dHeight);
iframe.height = height;
console.log(height);
}catch (ex){}
}
window.setInterval("reinitIframe()", 200);
</script>