javascript 模拟“ontype”事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7860084/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:33:19  来源:igfitidea点击:

Simulate an "ontype" event

javascriptjquery

提问by Randomblue

I want to simulate the Google Search effect that even with the search box not focused, the user can start typing and the input box will capture all keyboard strokes.

我想模拟谷歌搜索效果,即使搜索框没有聚焦,用户也可以开始输入,输入框将捕获所有键盘敲击。

I have looked for an ontypeevent, but haven't found anything. I know that the eventobject in callbacks for events like clickhas keyboard information, but I don't think this is what I'm after.

我一直在寻找一个ontype事件,但没有找到任何东西。我知道event事件回调中的对象click具有键盘信息,但我认为这不是我所追求的。

采纳答案by Randomblue

This does the job:

这可以完成以下工作:

 $(document).on('keydown', function() {
     $('input').focus();
 });

回答by Emre Erkan

HTML:

HTML:

<input type="text" id="txtSearch" />

Javascript:

Javascript:

var googleLikeKeyCapture = {
    inputField : null,
    documentKeydown: function(event) {
        var inputField = googleLikeKeyCapture.inputField;
        if(event.target != inputField.get(0)) {
            event.target = inputField.get(0);
            inputField.focus();
        }
    },
    init: function() {
        googleLikeKeyCapture.inputField = $('#txtSearch');
        $(document).bind('keydown', googleLikeKeyCapture.documentKeydown);
        googleLikeKeyCapture.inputField
            .focus(function() {
                $(document).unbind('keydown');
            })
            .blur(function() {
                $(document).bind('keydown', googleLikeKeyCapture.documentKeydown);
            });
        googleLikeKeyCapture.init = function() {};
    }
};

$(googleLikeKeyCapture.init);

Also you can find jsFiddle example here

您也可以在此处找到 jsFiddle 示例

EDIT :

编辑 :

And now it's a jQuery plugin. :) If keydown occures in a textarea or input field it doesn't capture keys, anything else goes to designated input field. If your selector matches more than one element it only uses the first element.

现在它是一个jQuery 插件。:) 如果 keydown 发生在 textarea 或输入字段中,它不会捕获键,其他任何内容都会转到指定的输入字段。如果您的选择器匹配多个元素,则它只使用第一个元素。

Usage: $('#txtSearch').captureKeys();

用法: $('#txtSearch').captureKeys();

回答by Jakub Hampl

The event you are after is onkeypress.

您所追求的事件是onkeypress

回答by Alex Kamburov

Try this jQuery Text Change Event plugin:

试试这个 jQuery Text Change Event 插件:

http://www.zurb.com/playground/jquery-text-change-custom-event

http://www.zurb.com/playground/jquery-text-change-custom-event