触发特定的keyPress

时间:2017-03-10 16:35:55

标签: javascript reactjs keycode

所以我想在向下按键上触发'tab'事件,在up按键上触发'shift + tab'事件。这是我到目前为止所得到的,但我似乎无法设置Keypress事件的keyCode。我读到keyCode已被弃用,但我也尝试了代码(确实设置了),但它没有触发输入操作。

if (e.keyCode === 38) {
  // trigger a shift tab
  console.log('up key was pressed')
}

if (e.keyCode === 40) {
  console.log('down key was pressed')
  let event = new KeyboardEvent('keyPress', { keyCode: 9 })
  window.dispatchEvent(event)
}

1 个答案:

答案 0 :(得分:1)

https://jsfiddle.net/0Lv9bthd/18/捕获你需要keydown的向上和向下箭头按下,不能使用按键

window.addEventListener("keydown", function(e) {
    console.log(e.keyCode);
    if (e.keyCode == 38) {
    console.log('up key was pressed');
  }
});