jQuery $.focus() 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15859113/
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
$.focus() not working
提问by Sam Selikoff
The last example of jQuery's focus()
documentationstates
$('#id').focus()
should make the input focused (active). I can't seem to get this working.
应该使输入集中(活动)。我似乎无法让这个工作。
Even in the console on this site, I'm trying it for the search box
即使在本网站的控制台中,我也在尝试搜索框
$('input[name="q"]').focus()
and I'm getting nothing. Any ideas?
而我一无所获。有任何想法吗?
回答by Justin Warkentin
Actually the example you gave for focusing on this site works just fine, as long as you're not focused in the console. The reason that's not working is simply because it's not stealing focus from the dev console. If you run the following code in your console and then quickly click in your browser window after, you will see it focus the search box:
实际上,只要您不专注于控制台,您提供的关注此站点的示例就可以正常工作。不起作用的原因仅仅是因为它没有从开发控制台窃取焦点。如果您在控制台中运行以下代码,然后在浏览器窗口中快速单击,您将看到它聚焦于搜索框:
setTimeout(function() { $('input[name="q"]').focus() }, 3000);
As for your other one, the one thing that has given me trouble in the past is order of events. You cannot call focus() on an element that hasn't been attached to the DOM. Has the element you are trying to focus already been attached to the DOM?
至于你的另一个,过去给我带来麻烦的一件事是事件的顺序。您不能对尚未附加到 DOM 的元素调用 focus()。您尝试聚焦的元素是否已附加到 DOM?
回答by Cymro
Found a solution elsewhere on the net...
在网上的其他地方找到了解决方案......
$('#id').focus();
did not work.
不工作。
$('#id').get(0).focus();
did work.
没有工作。
回答by DroidOS
Some of the answers here suggest using setTimeout
to delay the process of focusing on the target element. One of them mentions that the target is inside a modal dialog. I cannot comment further on the correctness of the setTimeout
solution without knowing the specific details of where it was used. However, I thought I should provide an answer here to help out people who run into this thread just as I did
这里的一些答案建议使用setTimeout
来延迟关注目标元素的过程。其中之一提到目标在模态对话框内。在setTimeout
不知道解决方案的具体使用细节的情况下,我无法进一步评论解决方案的正确性。但是,我想我应该在这里提供一个答案,以帮助像我一样遇到此线程的人
The simple fact of the matter is that you cannot focus on an element which is not yet visible. If you run into this problem ensure that the target is actually visiblewhen the attempt to focus it is made. In my own case I was doing something along these lines
事情的简单事实是,您无法将注意力集中在尚不可见的元素上。如果遇到此问题,请确保在尝试聚焦时目标实际上是可见的。在我自己的情况下,我正在做这些事情
$('#elementid').animate({left:0,duration:'slow'});
$('#elementid').focus();
This did not work. I only realized what was going on when I executed $('#elementid').focus()` from the console which didwork. The difference - in my code above the target there is no certainty that the target will infact be visible since the animation may not be complete. And there lies the clue
这没有用。当我从确实有效的控制台执行 $('#elementid').focus()` 时,我才意识到发生了什么。不同之处 - 在目标上方的代码中,不能确定目标实际上是否可见,因为动画可能不完整。这就是线索
$('#elementid').animate({left:0,duration:'slow',complete:focusFunction});
function focusFunction(){$('#elementid').focus();}
works just as expected. I too had initially put in a setTimeout
solution and it worked too. However, an arbitrarily chosen timeout is bound to break the solution sooner or later depending on how slowly the host device goes about the process of ensuring that the target element is visible.
工作正常。我也最初提出了一个setTimeout
解决方案,它也有效。然而,根据主机设备在确保目标元素可见的过程中运行的速度,任意选择的超时迟早会破坏解决方案。
回答by Wolf359
if you use bootstrap + modal, this worked for me :
如果您使用 bootstrap + modal,这对我有用:
$(myModal).modal('toggle');
$(myModal).on('shown.bs.modal', function() {
$('#modalSearchBox').focus()
});
回答by Ben
Just in case anybody else stumbles across this question and had the same situation I had - I was trying to set the focus after clicking on another element, yet the focus didn't appear to work. It turns out I just needed an e.preventDefault();
- here's an example:
以防万一其他人偶然发现这个问题并遇到与我相同的情况 - 我试图在单击另一个元素后设置焦点,但焦点似乎不起作用。事实证明我只需要一个e.preventDefault();
- 这是一个例子:
$('#recipients ul li').mousedown(function(e) {
// add recipient to list
...
// focus back onto the input
$('#message_recipient_input').focus();
// prevent the focus from leaving
e.preventDefault();
});
This helped:
这有助于:
If you call HTMLElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the HTMLElement. Source: https://developer.mozilla.org/en/docs/Web/API/HTMLElement/focus
如果从 mousedown 事件处理程序调用 HTMLElement.focus(),则必须调用 event.preventDefault() 以防止焦点离开 HTMLElement。来源:https: //developer.mozilla.org/en/docs/Web/API/HTMLElement/focus
回答by user3861385
I realize this is old, but came across it today. None of the answers worked for me, what I did find that worked was setTimeout. I wanted my focus to be placed on the input filed of a modal, using the setTimeout worked. Hope this helps!
我意识到这是旧的,但今天遇到了它。没有一个答案对我有用,我确实发现有效的是 setTimeout。我希望我的重点放在模态的输入字段上,使用 setTimeout 工作。希望这可以帮助!
回答by Kumar Shubham
I also had this problem. The solution that worked in my case was using the tabindex property on the HTML element.
我也有这个问题。在我的案例中有效的解决方案是在 HTML 元素上使用 tabindex 属性。
I was using ng-repeat
for some li elements inside a list and I was not able to bring focus to the first li using .focus(), so I simply added the tabindex attribute to each li during the loop.
我ng-repeat
在列表中使用了一些 li 元素,但我无法使用 .focus() 将焦点移至第一个 li,因此我只是在循环期间将 tabindex 属性添加到每个 li。
so now <li ng-repeat="user in users track by $index" tabindex="{{$index+1}}"></li>
所以现在 <li ng-repeat="user in users track by $index" tabindex="{{$index+1}}"></li>
That +1 was index starts from 0. Also make sure that the element is present in DOM before calling the .focus() function
+1 是索引从 0 开始。还要确保在调用 .focus() 函数之前该元素存在于 DOM 中
I hope this helps.
我希望这有帮助。
回答by Rolando Retana
For those with the problem of not working because you used "$(element).show()". I solved it the next way:
对于那些因为使用“$(element).show()”而无法工作的问题。我用下一个方法解决了它:
var textbox = $("#otherOption");
textbox.show("fast", function () {
textbox[0].focus();
});
So you dont need a timer, it will execute after the show method is completed.
所以你不需要计时器,它会在 show 方法完成后执行。
回答by Abel
Add a delay before focus(). 200 ms is enough
在 focus() 之前添加一个延迟。200 毫秒就够了
function focusAndCursor(selector){
var input = $(selector);
setTimeout(function() {
// this focus on last character if input isn't empty
tmp = input.val(); input.focus().val("").blur().focus().val(tmp);
}, 200);
}
回答by aexl
Had this issue again just now, and believe it or not, all I had to do was close the developer tools. Apparently the Console tab has the focus priority over the page content.
刚才又遇到这个问题,不管你信不信,我所要做的就是关闭开发人员工具。显然,控制台选项卡的焦点优先于页面内容。