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

问题描述

我试图在Chrome上使用JavaScript将一个键盘事件触发到一个页面。
我有一种方法可以用于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);

$ / code>

其中key是所需的键,而keyCode将小写字母改为大写, charCodeAt()。



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



我也尝试过使用JQuery方法这里没有成功。

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

解决方案

我只想把这个基本片段放在那里。它在Chrome中运行,基于Paul Irish提到的黑客技术。

它使用charCode而不是keyCode(在某些情况下它可能很有用),但如果您愿意,可以适应keyCode。

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


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);
}

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

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.

EDIT: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.

解决方案

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上触发键盘事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 17:26