Javascript 在 JS/jQuery 中触发 keypress/keydown/keyup 事件?

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

Trigger a keypress/keydown/keyup event in JS/jQuery?

javascriptjquerydom-events

提问by Alex

What is the best way to simulate a user entering text in a text input box in JS and/or jQuery?

模拟用户在 JS 和/或 jQuery 的文本输入框中输入文本的最佳方法是什么?

I don'twant to actually put text in the input box, I just want to trigger all the event handlersthat would normally get triggered by a user typing info into a input box. This means focus, keydown, keypress, keyup, and blur. I think.

希望居然把文本输入框,我只是想触发所有的事件处理程序,通常会得到用户输入信息到一个输入框触发。这意味着焦点、keydown、keypress、keyup 和模糊。我认为。

So how would one accomplish this?

那么如何实现这一目标呢?

回答by ebynum

You can trigger any of the events with a direct call to them, like this:

您可以通过直接调用它们来触发任何事件,如下所示:

$(function() {
    $('item').keydown();
    $('item').keypress();
    $('item').keyup();
    $('item').blur();
});

Does that do what you're trying to do?

那做你想做的吗?

You should probably also trigger .focus()and potentially .change()

您可能还应该触发.focus()并可能.change()

If you want to trigger the key-events with specific keys, you can do so like this:

如果你想用特定的键触发键事件,你可以这样做:

$(function() {
    var e = $.Event('keypress');
    e.which = 65; // Character 'A'
    $('item').trigger(e);
});

There is some interesting discussion of the keypress events here: jQuery Event Keypress: Which key was pressed?, specifically regarding cross-browser compatability with the .which property.

这里有一些关于按键事件的有趣讨论:jQuery Event Keypress:哪个键被按下?,特别是关于与 .which 属性的跨浏览器兼容性。

回答by aljgom

You could dispatching events like

你可以调度事件,如

el.dispatchEvent(new Event('focus'));
el.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));

回答by cloakedninjas

To trigger an enterkeypress, I had to modify @ebynum response, specifically, using the keyCode property.

要触发enter按键,我必须修改 @ebynum 响应,特别是使用 keyCode 属性。

e = $.Event('keyup');
e.keyCode= 13; // enter
$('input').trigger(e);

回答by Sionnach733

Here's a vanilla js example to trigger any event:

这是一个触发任何事件的普通 js 示例:

function triggerEvent(el, type){
if ('createEvent' in document) {
        // modern browsers, IE9+
        var e = document.createEvent('HTMLEvents');
        e.initEvent(type, false, true);
        el.dispatchEvent(e);
    } else {
        // IE 8
        var e = document.createEventObject();
        e.eventType = type;
        el.fireEvent('on'+e.eventType, e);
    }
}

回答by JSON C11

You can achieve this with: EventTarget.dispatchEvent(event)and by passing in a new KeyboardEvent as the event.

您可以通过以下方式实现:EventTarget.dispatchEvent(event)并传入一个新的 KeyboardEvent 作为事件。

For example: element.dispatchEvent(new KeyboardEvent('keypress', {'key': 'a'}))

例如: element.dispatchEvent(new KeyboardEvent('keypress', {'key': 'a'}))

Working example:

工作示例:

// get the element in question
const input = document.getElementsByTagName("input")[0];

// focus on the input element
input.focus();

// add event listeners to the input element
input.addEventListener('keypress', (event) => {
  console.log("You have pressed key: ", event.key);
});

input.addEventListener('keydown', (event) => {
  console.log(`key: ${event.key} has been pressed down`);
});

input.addEventListener('keyup', (event) => {
  console.log(`key: ${event.key} has been released`);
});

// dispatch keyboard events
input.dispatchEvent(new KeyboardEvent('keypress',  {'key':'h'}));
input.dispatchEvent(new KeyboardEvent('keydown',  {'key':'e'}));
input.dispatchEvent(new KeyboardEvent('keyup', {'key':'y'}));
<input type="text" placeholder="foo" />

MDN dispatchEvent

MDN 调度事件

MDN KeyboardEvent

MDN 键盘事件

回答by simonzack

You're now able to do:

您现在可以执行以下操作:

var e = $.Event("keydown", {keyCode: 64});

回答by yuliskov

First of all, I need to say that sample from Sionnach733worked flawlessly. Some users complain about absent of actual examples. Here is my two cents. I've been working on mouse click simulation when using this site: https://www.youtube.com/tv. You can open any video and try run this code. It performs switch to next video.

首先,我需要说来自Sionnach733 的样本完美无缺。一些用户抱怨缺少实际示例。这是我的两分钱。使用本网站时,我一直在研究鼠标点击模拟:https: //www.youtube.com/tv。您可以打开任何视频并尝试运行此代码。它执行切换到下一个视频。

function triggerEvent(el, type, keyCode) {
    if ('createEvent' in document) {
            // modern browsers, IE9+
            var e = document.createEvent('HTMLEvents');
            e.keyCode = keyCode;
            e.initEvent(type, false, true);
            el.dispatchEvent(e);
    } else {
        // IE 8
        var e = document.createEventObject();
        e.keyCode = keyCode;
        e.eventType = type;
        el.fireEvent('on'+e.eventType, e);
    }
}

var nextButton = document.getElementsByClassName('icon-player-next')[0];
triggerEvent(nextButton, 'keyup', 13); // simulate mouse/enter key press

回答by Eugen Sunic

For typescript cast to KeyboardEventInit and provide the correct keyCode integer

对于 typescript 转换为 KeyboardEventInit 并提供正确的 keyCode 整数

const event = new KeyboardEvent("keydown", {
          keyCode: 38,
        } as KeyboardEventInit);

回答by Fabien Haddadi

I thought I would draw your attention that in the specific context where a listener was defined within a jQuery plugin, then the only thing that successfully simulated the keypress event for me, eventually caught by that listener, was to use setTimeout(). e.g.

我想我会提请您注意,在 jQuery 插件中定义侦听器的特定上下文中,唯一为我成功模拟按键事件(最终被该侦听器捕获)的方法是使用 setTimeout()。例如

setTimeout(function() { $("#txtName").keypress() } , 1000);

Any use of $("#txtName").keypress()was ignored, although placed at the end of the .ready() function. No particular DOM supplement was being created asynchronously anyway.

任何使用都$("#txtName").keypress()忽略,尽管放置在.ready() function. 无论如何都没有异步创建特定的 DOM 补充。