Set input field focus on start typing

爱⌒轻易说出口 提交于 2019-12-10 09:35:50

问题


I am looking for a way to be able to start typing on a website without having selected anything and then have a specific input field in focus.

Google also employs this feature. In their search results you can click anywhere (defocus the search field) and when you start typing it automatically focuses on the search field again.

I was thinking about jQuery general onkeyup function to focus on the field, any suggestions?

Much appreciated.


回答1:


You should bind the keydown event, but unbind it immediately so that typing may continue in other text inputs without reverting focus to the default input.

$(document).bind('keydown',function(e){
    $('#defaultInput').focus();
    $(document).unbind('keydown');
});

See example here.




回答2:


This solution does not have the problem that @mVChr's solution has: Ie you can click on another input with the mouse and start typing without losing focus due to the keydown-binding.

Also this solution does not remove all the element's keydown-bindings, but uses a named handler instead.

var default_input_handler = function() {
    $('.default-input').focus();
    $(document).off('keydown', default_input_handler);
}

$(document).on('keydown', default_input_handler);

$('input, textarea, select').on('focus', function() {
    $(document).off('keydown', default_input_handler);
});



回答3:


If planning to do this I'd say use onKeyUp instead of onKeyDown. Its much earlier in the action which would help ease the flow of the interaction.




回答4:


The answer is as simple as this:

$(document).keydown(function() { $('#element').focus(); });

keydown is preferred after all because keyup will only be fired after the first key is pressed - and respectively not capture the first key typed in my search field.



来源:https://stackoverflow.com/questions/4840407/set-input-field-focus-on-start-typing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!