首页  >  文章  >  web前端  >  Chrome中模拟Keydown时,为什么会注册错误的Key?

Chrome中模拟Keydown时,为什么会注册错误的Key?

Susan Sarandon
Susan Sarandon原创
2024-10-18 13:16:30838浏览

When Simulating Keydown in Chrome, Why Does the Wrong Key Get Registered?

Chrome 中的按键模拟正常触发,但按键不正确

在 Chrome 中的文本区域元素上模拟按键事件对于定制用户交互至关重要。但是,某些尝试可能会产生意外结果。

您尝试使用 initKeyboardEvent 和所需的 keyCode 启动 keydown 事件,但文本区域最终注册了不正确的键值(Enter 而不是预期的字母)。另一种涉及属性覆盖的替代方法也被证明是不成功的。

要解决此问题,除了“keyCode”之外,您还需要覆盖“which”属性。这是修改后的代码示例:

<code class="js">document.addEventListener('keydown', e => console.log(
  'altKey                : ' + e.altKey + '\n' +
  'charCode (Deprecated) : ' + e.charCode + '\n' +
  'code                  : ' + e.code + '\n' +
  'ctrlKey               : ' + e.ctrlKey + '\n' +
  'isComposing           : ' + e.isComposing + '\n' +
  'key                   : ' + e.key + '\n' +
  'keyCode (Deprecated)  : ' + e.keyCode + '\n' +
  'location              : ' + e.location + '\n' +
  'metaKey               : ' + e.metaKey + '\n' +
  'repeat                : ' + e.repeat + '\n' +
  'shiftKey              : ' + e.shiftKey + '\n' +
  'which (Deprecated)    : ' + e.which + '\n' +
  'isTrusted             : ' + e.isTrusted + '\n' +
  'type                  : ' + e.type
));

const Podium = {};
Podium.keydown = function(k) {
  const oEvent = document.createEvent('KeyboardEvent');

  // Chromium Hack
  Object.defineProperty(
    oEvent,
    'keyCode',
    {
       get : function() {
         return this.keyCodeVal;
       }
    }
  );
  Object.defineProperty(
    oEvent,
    'which',
    {
       get : function() {
         return this.keyCodeVal;
       }
    }
  );

  if (oEvent.initKeyboardEvent) {
    oEvent.initKeyboardEvent("keydown", true, true, document.defaultView,
                             false, false, false, false, k, k);
  }
  else {
      oEvent.initKeyEvent("keydown", true, true, document.defaultView,
                          false, false, false, false, k, 0);
  }

  oEvent.keyCodeVal = k;

  if (oEvent.keyCode !== k) {
    alert("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")");
  }

  document.dispatchEvent(oEvent);
}

//Sample usage
Podium.keydown(65);</code>

通过覆盖“keyCode”和“which”,您可以确保在 keydown 事件期间注册正确的键代码和相应的键。这种方法纠正了不正确的按键注册问题,并允许准确的按键模拟。

以上是Chrome中模拟Keydown时,为什么会注册错误的Key?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn