Javascript - 触发特定的键盘键

时间:2015-08-03 10:28:31

标签: javascript events triggers keyboard

我有这段代码:

window.addEventListener('keydown', function (e) { 
   console.log(e.which); 
   console.log(e.keyCode); 
});

 var evObj = new KeyboardEvent('keydown', {key:65});
 window.dispatchEvent(evObj);

为什么我在控制台看到0而不是65?

e.keyCode和e.which都是0而不是65,我在Chrome最新版本

非常感谢你。

3 个答案:

答案 0 :(得分:5)

Chrome中存在错误,keyCodewhich无法配置。

可能的工作方式:定义自定义getter



 window.addEventListener('keydown', function (e) { console.log(e.which); });
 
 (function(o,k){
    //use createEvent for better compatibility
   var evObj = document.createEvent('HTMLEvents');
    evObj.initEvent('keydown', true, false);
    Object.defineProperty(evObj, 'keyCode', {
      get: function() {
        return k;
      }
    });
    Object.defineProperty(evObj, 'which', {
      get: function() {
        return k;
      }
    });
    o.dispatchEvent(evObj); 
 }(window,65));




答案 1 :(得分:4)

  

e.keyCode和e.which都是0而不是65,我在Chrome最新版本

因为您设置的是RewriteRule ^ %{REQUEST_URI}? [R,L] ,而不是keykeyCodeAccording to MDNwhich表示密钥,而不是密钥代码。要初始化key和/或keyCode,您应该......执行此操作(请参阅MDN's article on KeyboardEvent)。

which

以下是一个示例,但它似乎无法在Chrome中运行(仍然获得var evObj = new KeyboardEvent('keydown', {keyCode:65, which:65}); ) - 这是一个Chrome错误,下面是解决方法。在Firefox中有效。在IE11中失败,因为IE11不喜欢0

new KeyboardEvent
window.addEventListener("keydown", function(e) {
  snippet.log("keyCode = " + e.keyCode + ", which = " + e.which);
}, false);
setTimeout(function() {
  var evObj = new KeyboardEvent('keydown', {keyCode:65, which:65});
  snippet.log("Sending event");
  window.dispatchEvent(evObj);
}, 300);

您可以使用the technique from this answer

解决Chrome错误

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
window.addEventListener("keydown", function(e) {
  snippet.log("keyCode = " + e.keyCode + ", which = " + e.which);
}, false);
setTimeout(function() {
  var evObj = new KeyboardEvent('keydown', {keyCode:65, which:65});
  // Chrome bug workaround:
  if (evObj.keyCode != 65) {
    Object.defineProperty(evObj, "keyCode", {
      value: 65
    });
    Object.defineProperty(evObj, "which", {
      value: 65
    });
  }
  snippet.log("Sending event");
  window.dispatchEvent(evObj);
}, 300);

答案 2 :(得分:-1)

注意:在Firefox中,keyCode属性不适用于onkeypress事件(仅返回0)。对于跨浏览器解决方案,请将which属性与keyCode一起使用,例如:

&#13;
&#13;
var x = event.which || event.keyCode;  // Use either which or keyCode, depending on browser support
&#13;
&#13;
&#13;