在Web软件开发过程中,经常会需要弹出一个窗口,并且在子窗口和父窗口之间通信,并且子窗口要能锁住父窗口。比较常见的是window.showModalDialog(),这种方法有很多局限性,比如窗口之间的通信不方便,只在ie下有效等。如果采用window.open()的方式,子窗口又不能锁住父窗口。网上有许多通过层来屏蔽父窗口的例子,但是也都没能完全锁定父窗口。经过考虑,楼主我决定采用一种变通的办法:锁定父窗口-> 阻止父窗口获得焦点->当父窗口获得焦点时,将焦点转移到子窗口。
代码如下:
父窗口网页parent.html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script language="javascript">
window.onfocus = function focus(){//重写父窗口window对象中的onfocus,使其在获得焦点时执行以下代码
if( typeof(window.childWindow)!="undefined"){//如果子窗口存在,将焦点转到子窗口
window.childWindow.focus();
}
}
function showChild(){
//打开一个子窗口,并将子窗口的引用保存在父窗口window的childWindow属性中
window.childWindow = window.open("child.html","child","width=300px,height=110px,resizable=no,scroll=no,status=no");
window.childWindow.focus();
}
</script>
</head>
<body>
<input name="btn_show" type="button" value="显示子窗口" οnclick="showChild()" />
<input name="btn_alert" type="button" value="显示其他" οnclick="alert('被调用了')" />
</body>
</html>
子窗口网页 child.html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script language="javascript">
window.onunload = function unload(){
window.opener.childWindow = undefined;
}
</script>
</head>
<body>
这是子窗口!
</body>
</html>