KeyboardEvent.keyCode deprecated. What does this mean in practice?

前端 未结 6 1124
甜味超标
甜味超标 2020-12-23 02:36

According to MDN, we should most definitely not be using the .keyCode property. It is deprecated:

https://developer.mozilla.org/en-US/do

6条回答
  •  没有蜡笔的小新
    2020-12-23 03:17

    MDN has already provided a solution:

    https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

    window.addEventListener("keydown", function (event) {
      if (event.defaultPrevented) {
        return; // Should do nothing if the default action has been cancelled
      }
    
      var handled = false;
      if (event.key !== undefined) {
        // Handle the event with KeyboardEvent.key and set handled true.
      } else if (event.keyIdentifier !== undefined) {
        // Handle the event with KeyboardEvent.keyIdentifier and set handled true.
      } else if (event.keyCode !== undefined) {
        // Handle the event with KeyboardEvent.keyCode and set handled true.
      }
    
      if (handled) {
        // Suppress "double action" if event handled
        event.preventDefault();
      }
    }, true);
    

提交回复
热议问题