gpt4 book ai didi

javascript - 如何使用自定义键盘事件和 keyCode 更改输入/文本区域值?

转载 作者:行者123 更新时间:2023-11-30 17:04:03 30 4
gpt4 key购买 nike

我想通过触发键盘事件来填充文本区域,例如 keydown(我正在为测试用例这样做)。

我添加了一个片段(如下)来显示我用来创建和触发事件的代码。事件触发,但文本区域从未收到 keyCode 的值,即字母 A。

我需要做什么才能看到文本区域中的字母?我目前正在 Chrome 控制台中运行该代码段,但它也应该可以在 IE9 中运行。

var t = document.getElementById('foo');

// Event creation
var event = document.createEvent('HTMLEvents');
event.initEvent('keydown', true, true);
event.keyCode = 65;
event.which = 65;

// Listener for demo purpose
t.addEventListener('keydown', function (e) {
document.getElementById('fired').value = e.type + ' fired';
});

// Event trigger
t.dispatchEvent(event);
<textarea id="foo"></textarea>

<br>
<input id="fired" value="">

最佳答案

为什么触发后值没有变化 keydown

简而言之:您无法更改 input 的值/texarea与调度KeyboardEvent以编程方式。

字符实际上是如何进入 input 的? ?在 MDN 上你可以找到 Keyboardevent sequence 的描述(假设未调用 preventDefault):

  • A keydown event is first fired. If the key is held down further and the key produces a character key, then the event continues to be emitted in a platform implementation dependent interval and the KeyboardEvent.repeat read only property is set to true.
  • If the key produces a character key that would result in a character being inserted into possibly an <input>, <textarea> or an element with HTMLElement.contentEditable set to true, the beforeinput and input event types are fired in that order. Note that some other implementations may fire keypress event if supported. The events will be fired repeatedly while the key is held down.
  • A keyup event is fired once the key is released. This completes the process.

所以,keydown导致 input默认事件。但这仅适用于 trusted events。 :

Most untrusted events will not trigger default actions, with the exception of the click event... All other untrusted events behave as if the preventDefault() method had been called on that event.

基本上受信任的事件是由用户发起的事件,而不受信任的事件是由脚本发起的。在大多数浏览器中,每个事件都有一个属性 isTrusted指示事件是否可信。

以及如何测试KeyboardEvent关于 input那么呢?

嗯,首先,想想你是否真的需要一个 KeyboardEvent处理程序。也许你可以在 InputEvent 中做任何事情处理程序。这意味着您只需设置 input 的值即可。在你的测试中然后触发 InputEvent .

如果你还需要KeyboardEvent处理程序比它取决于它发生了什么。例如。如果你调用preventDefault在某些情况下,您可以使用 spy 检查它是否在测试中被调用。这是 sinon 的示例作为 spy 和chai作为断言库。

const myEvent = new KeyboardEvent('keydown', { key: 'a' })
sinon.spy(myEvent, 'preventDefault')
document.getElementById('foo').dispatchEvent(myEvent)
expect(myEvent.preventDefault.calledOnce).to.equal(true)

关于javascript - 如何使用自定义键盘事件和 keyCode 更改输入/文本区域值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28344685/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com