window.open 模拟模态窗口效果

本文介绍了一种使用JavaScript在Web开发中实现子窗口锁定父窗口的方法。通过重写父窗口的onfocus事件,确保父窗口无法获得焦点,同时将焦点强制转移至子窗口,实现了子窗口对用户的强制关注。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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="显示子窗口" onclick="showChild()" />  
<input name="btn_alert" type="button" value="显示其他" onclick="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>

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值