日期:2014-05-16  浏览次数:20341 次

javascript关闭子窗口
最近项目中要用到js关闭所有打开的子窗口,包括window.open打开的和<a href="" target="_blank">超链接打开的窗口,父窗口关闭,所有的子窗口自动关闭
javascript代码如下(c.js):
var subWin = null;
var subWinList = new Array();

function showWin(){
	 if (!document.getElementsByTagName) return false;
	 var links = document.getElementsByTagName("a");
	 for ( var i=0; i < links.length; i++) {
		 links[i].onclick =  function(){
			if(this.getAttribute('target')=='_blank' ) {
			  subWin = window.open(this.getAttribute('href'));
			  subWinList.push(subWin);
			  return false;
			}
		}
	 }
}
function openwindow(url,name,iWidth,iHeight)
{
    var url;
    var name;
    var iWidth;
    var iHeight;
    var iTop = (window.screen.availHeight-30-iHeight)/2;
    var iLeft = (window.screen.availWidth-10-iWidth)/2;
    subWin=window.open(url,name,'height='+iHeight+',innerHeight='+iHeight+',width='+iWidth+',innerWidth='+iWidth+',top='+iTop+',left='+iLeft+',toolbar=no,location=no,status=yes,scrollbars=yes,resizable=yes,directoried=no,menubar=no');
	subWinList.push(subWin);
}
function closeChild(){
	if (subWin && subWin.open && !subWin.closed){
		subWin.close();
	}
	for(i=0;i<subWinList.length;i++){
		subWinList[i].close();
	}
}
window.attachEvent("onload",showWin);
window.onunload=closeChild;


主要思路是把<a>标签打开的页面也用window.open()打开。

<html>
<head>
<script type="text/javascript" src="c.js"></script>
</head>
<body>
<a href="b.html" target="_blank">hello</a>
<a href="b.html" target="_blank">hello</a>
<a href="b.html" target="_blank">hello</a>
<a href="b.html" target="_blank">hello</a>
<a href="b.html" target="_blank">hello</a>
<a href="b.html" target="_blank">hello</a>
<a href="b.html" target="_blank">hello</a>
<a href="b.html" target="_blank">hello</a>
<a href="b.html" target="_blank">hello</a>
<input type="button" name="sub" value="打开新窗口" onclick="openwindow("b.html","",500,600)">
</body>
</html>
1 楼 liliugen 2010-08-26  
跑不起来。不是完整版本。希望给出一个demo出来
2 楼 javavsphper 2010-08-26  
liliugen 写道
跑不起来。不是完整版本。希望给出一个demo出来

OK 代码已放出,主要是IE上跑
3 楼 我爱小白 2010-08-26