本文介绍了在 Chrome 上触发键盘事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Chrome 上使用 javascript 向页面触发键盘事件.我有一种曾经在 Firefox 上工作的方法:

I'm trying to fire a keyboard event to a page using javascript on Chrome.I had an approach that used to work on Firefox:

pressKey = function(key, shift) {
  var evt = document.createEvent('KeyboardEvent');
  evt.initKeyEvent("keypress", false, true, null, false, false,
                   shift, false, keyCode(key), key.charCodeAt(0));
  document.dispatchEvent(evt);
}

其中 key 是所需的键,keyCode 将小写字母更改为大写字母并调用 charCodeAt().

where key is the desired key and keyCode changes lowercase letters into highercase and also calls charCodeAt().

我的问题是 Safari/Chrome 上的事件没有 initKeyEvent,而是 initKeyboardEvent.我注意到的主要区别是您必须将密钥作为 keyIdentifier(看起来像一个 unicode 字符)传递,而不是传递 keycode 和 keychar.尽管如此,我仍然无法让它发挥作用.

My problem is that events on Safari/Chrome don't have initKeyEvent, but initKeyboardEvent. The main difference I could notice was that you have to pass the key as a keyIdentifier (which looks like a unicode character) instead of passing the keycode and the keychar. Nonetheless I still can't manage to make it work.

我也尝试过 这里没有成功.

I've also tried the JQuery approach described here without success.

我进一步调试了这一点,似乎 Chrome 上的事件确实触发了侦听器,但 keyCode/charCode 始终为 0.我尝试设置 evt.keyCode 或 evt.charCode 也没有成功.

I debugged this a little further and it seems that the event on Chrome does trigger the listeners, but keyCode/charCode is always 0. I've tried to set evt.keyCode or evt.charCode with no success either.

推荐答案

我只想把这个基本的片段扔到那里去.它在 Chrome 中运行,并且基于 Paul Irish 提到的 hack.
它使用 charCode 而不是 keyCode(这在某些情况下很有用),但如果你愿意,可以适应 keyCode.

I just want to throw this basic snippet out there. It works in Chrome and is based on the hack mentioned by Paul Irish.
It uses charCode instead of keyCode (which can be useful in certain situation), but adapt to keyCode if you so please.

var keyboardEvent = new KeyboardEvent('keypress', {bubbles:true});
Object.defineProperty(keyboardEvent, 'charCode', {get:function(){return this.charCodeVal;}});
keyboardEvent.charCodeVal = [your char code];
document.body.dispatchEvent(keyboardEvent);

这篇关于在 Chrome 上触发键盘事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 09:34