我需要用 JavaScript 在后台打开一个新窗口,并确保原来的窗口仍然是焦点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2181464/
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
I need to open a new window in the background with JavaScript, and make sure the original is still focused
提问by IsaacL
I have a window I'm opening with a Javascript function:
我有一个使用 Javascript 函数打开的窗口:
function newwindow()
{
window.open('link.html','','width=,height=,resizable=no');
}
I need it that once the new window opens that the focus returns to the original window. How can I do that? And where do I put the code - in the new window, or the old one? Thanks!
我需要的是,一旦新窗口打开,焦点就会返回到原始窗口。我怎样才能做到这一点?我应该把代码放在哪里 - 在新窗口中还是在旧窗口中?谢谢!
回答by ChadT
This is known as a 'pop-under' (and is generally frowned upon... but I digress).. It should give you plenty to google about
这被称为“弹出窗口”(并且通常不赞成......但我离题了......它应该给你很多关于谷歌的信息
You probably want to do something like:
您可能想要执行以下操作:
var popup = window.open(...);
popup.blur();
window.focus();
Which should set the focus back to the original window (untested - pinched from google). Some browsers might block this technique.
这应该将焦点设置回原始窗口(未经测试 - 从谷歌捏)。某些浏览器可能会阻止此技术。
回答by Albert
After calling window.open, you may try to use
调用window.open后,您可以尝试使用
window.resizeTo(0,0);
window.moveTo(0,window.screen.availHeight+10);
this way can not really open window in background, but works in similar way. Chrome works fine, did not try other browser.
这种方式不能真正在后台打开窗口,但以类似的方式工作。Chrome 工作正常,没有尝试其他浏览器。
回答by aljgom
If Albert's solutiondoesn't work for you and you actually want the window visible, but to be opened behind the current window, you can try opening a new tab in the opener window and closing it right away, this will bring the focus back to the opener window.
如果Albert 的解决方案对您不起作用,并且您实际上希望窗口可见,但要在当前窗口后面打开,您可以尝试在打开窗口中打开一个新选项卡并立即关闭它,这将使焦点回到开门窗。
window.open('link.html','','width=,height=,resizable=no');
window.open().close();
However, I believe whether the second window opens in a tab or a new window depends on your browser settings.
但是,我相信第二个窗口是在选项卡中打开还是在新窗口中打开取决于您的浏览器设置。
Please don't use "pop-unders" for evil.
请不要将“pop-unders”用于邪恶。
回答by Nazmul
You can use either "blur" or "focus" to do that required action.
您可以使用“模糊”或“聚焦”来执行所需的操作。
"blur"
“模糊”
function newwindow()
{
var myChild= window.open('link.html','','width=,height=,resizable=no');
myChild.blur();
}
"focus"
“重点”
function newwindow()
{
window.open('link.html','','width=,height=,resizable=no');
window.focus();
}
Put the code in your parentWindow (i.e. the window in which you are now)
将代码放在您的 parentWindow(即您现在所在的窗口)中
Both will work.
两者都会起作用。

