iframe 父子页面方法调用

时间:2023-03-09 00:21:00
iframe 父子页面方法调用

在写代码的时候经常会用到将一个网页嵌入到另一个网页中,w3c也规定了一个标签<iframe>,这个标签本身就支持跨域,而且所有的浏览器都支持

iframe具有以下属性:

1、frameborder 设为1代表显示周围边框,设置为0不显示周围边框

2、height 设置iframe的高度

3、width 设置iframe的宽度

4、longdesc 属性值为URL 规定一个页面,该页面包含了有关 iframe 的较长描述

5、marginheight 定义 iframe 的顶部和底部的边距

6、marginwidth 定义 iframe 的左侧和右侧的边距

7、name 规定 iframe 的名称

8、sandbox 启用一系列对 <iframe> 中内容的额外限制。

9、scrolling 设置为 yes 代表显示滚动条,设置为no代表不显示滚动条,设置为auto 代表自动

10、seamless 属性值也是 seamless 规定 <iframe> 看上去像是包含文档的一部分

11、src 规定在 iframe 中显示的文档的 URL

12、srcdoc 规定在 <iframe> 中显示的页面的 HTML 内容

那么在设置好了之后如果在父页面中想要调用子页面的方法,或者在子页面中调用父页面的方法怎么办呢??这个问题网上也很多介绍

父页面

<!DOCTYPE html>
<html >
<head>
<title>Parent Page</title>
<script language="javascript" type="text/javascript">
function parenttest() {
alert("这是父页面的方法!");
}
function btnClick() {
document.getElementById("childframe").contentWindow.childtest();
}
</script>
</head>
<body>
<div style="margin:auto;">
<h1>This is the Parent Page.</h1>
<input type="button" value="调用子页面的方法" onclick="btnClick()"/>
</div>
<div style="margin:auto;">
<iframe style="width:300px; height:300px;" id="childframe" src="son.html"></iframe>
</div>
</body>
</html>

子页面

<!DOCTYPE html>
<html >
<head>
<title>Child Page</title>
<script language="javascript" type="text/javascript">
function childtest() {
alert("这是子页面的方法!");
}
function btnClick() {
window.parent.parenttest();
}
</script>
</head>
<body>
<div style="margin:auto;">
<h1>This is the Child Page.</h1>
<input type="button" value="调用父页面的方法" onclick="btnClick()"/>
</div>
</body>
</html>

这样就可以实现子页面与父页面方法的相互调用,拥有这个方法在处理起来非常的方便。