简体   繁体   English

带有开放开发者控制台的 element.focus() 不工作

[英]element.focus() with open developer console not working

I want to programmatically focus on an input:我想以编程方式关注输入:

document.getElementById('widgetu25071_input').focus()

This does not work when the developer console is open.当开发人员控制台打开时,这不起作用。 Is there some way to do it without closing the console first?有没有先关闭控制台的方法?

You can recreate the issue on google.com:您可以在 google.com 上重新创建问题:

Open console and execute:打开控制台并执行:

document.getElementById('lst-ib').focus();

result for me: does not focus结果对我来说:不专注

now try: open console and execute:现在尝试:打开控制台并执行:

setTimeout(function() {
document.getElementById('lst-ib').focus();
}, 9000);

close console quickly.快速关闭控制台。 Focus works when the timeout is finished.超时完成后,焦点开始工作。

I forget about this every couple years and it drives me crazy until I remember again.我每隔几年就会忘记这件事,这让我发疯,直到我再次记起来。 So I'm adding an answer for myself and anyone else...所以我要为自己和其他人添加一个答案......

JavaScript basically thinks you're in a different application and can't steal focus to focus wherever you want to focus. JavaScript 基本上认为你在不同的应用程序中,无法窃取焦点以将焦点集中在你想集中的地方。 ;) You'll find this behavior if your cursor is in the console or in the URL bar of the browser. ;) 如果您的 cursor 在控制台或浏览器的 URL 栏中,您会发现此行为。

Mouse hover events will still fire but you won't be able to gain focus anywhere on the page unless focus is already on the actual page.鼠标 hover 事件仍会触发,但除非焦点已经在实际页面上,否则您将无法在页面上的任何位置获得焦点。

So for example, if you have a little popup that contains a text field and it shows on mouse hover of some other element, you'll get the pop-up on mouse hover but you won't get that text field to focus if your cursor is in the console or in the URL bar.因此,例如,如果您有一个包含文本字段的小弹出窗口,并且它显示在其他元素的鼠标 hover 上,您将在鼠标 hover 上看到弹出窗口,但如果您的cursor在控制台或URL栏中。

As a crazy guess I'd say without this, a bad programmer could keep you from navigating away from the page (or doing anything else) by stealing focus back to the page every time you click in the URL bar or the console.作为一个疯狂的猜测,如果没有这个,我会说一个糟糕的程序员可以通过在您每次单击 URL 栏或控制台时将焦点偷回页面来阻止您离开页面(或做任何其他事情)。

I hope this helps someone even if It's five years later.我希望这对某人有所帮助,即使是五年后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM