javascript 当焦点从中消失时如何关闭弹出窗口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9001599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to close a popup window when the focus is gone out from it
提问by jijo thomas
Requirement:A popup will be opened up from parent window, and it should get closed when the focus from the window is lost. (This should happen even when another application window is opened or came into focus).
要求:会从父窗口打开一个弹出窗口,当窗口失去焦点时它应该关闭。(即使打开另一个应用程序窗口或成为焦点,也应该发生这种情况)。
Tried code:<body onBlur='javascript:window.close();'>
试过的代码:<body onBlur='javascript:window.close();'>
Issue:On click within the body of the popup makes the popup closed.
问题:在弹出窗口主体内单击会使弹出窗口关闭。
Compatibility:ie6 and above, firefox.
兼容性:ie6及以上,firefox。
I got a workaroundfrom http://pro-thoughts.blogspot.com/2006/10/incorrect-behavior-of-windowonblur.html
我从http://pro-thoughts.blogspot.com/2006/10/incorrect-behavior-of-windowonblur.html得到了一个解决方法
var active_element;
var bIsMSIE;
function initiateSelfClosing() {
if (navigator.appName == "Microsoft Internet Explorer") {
active_element = document.activeElement;
document.onfocusout = closeWnd;
bIsMSIE = true;
}
else { window.onblur = closeWnd; }
}
function closeWnd() {
if (window.opener != null) {
if (bIsMSIE && (active_element != document.activeElement)) {
active_element = document.activeElement;
}
else {
window.close();
}
}
}
<body onload="initiateSelfClosing()">
</body>
But here also one problem is there, if there is a print button in the page, and if am clicking on print > then cancelling the print job, the popup is getting closed.
但这里还有一个问题,如果页面中有打印按钮,并且如果我点击打印 > 然后取消打印作业,弹出窗口就会关闭。
Can some one help me pls...
有人可以帮我吗请...
回答by Sami
Little corrections in sathishkumar's answer
sathishkumar 的回答中的小修正
1.we need to convert win
to jquery object
1.我们需要转换win
为jquery对象
2.Apply blur event on jqvariable and not on window
2.在 jqvariable 上应用模糊事件而不是在 window
3.this.close
is good enough in definition of onblur
event
3.事件this.close
定义足够好onblur
var win = window.open("URL");
var jqwin = $(win);
$(jqwin).blur(function() {
this.close();
});
回答by sathishkumar
Use document for blur event
使用文档进行模糊事件
var win = window.open("URL");
$(window).blur(function() {
win.close();
});
回答by Pranav
You cannot attach onblur event to BODY but
you Can attach a function on Onblur event of window.
您不能将 onblur 事件附加到 BODY,但
您可以在窗口的 Onblur 事件上附加一个函数。
<script type="text/javascript">
function closeme()
{
window.close();
}
window.onblur=closeme;
</script>
Since you have Edited your Question, You can get more help here
由于您已编辑问题,因此您可以在此处获得更多帮助