捕获可打印字符时keyDown跨浏览器键值/键码不一致问题的解决方案及keyPress适用性咨询
Hey there! Let's tackle your questions about handling printable keyboard characters now that keypress is deprecated.
Can I still use the keypress event?
Even though keypress is marked as deprecated in the spec, all major browsers (Chrome, Firefox, Safari, Edge) still support it today. If it's working reliably for your use case—especially with your bilingual keyboard—you can continue using it in the short term.
That said, deprecated features mean they could be removed in future browser updates, so it's wise to plan a migration to modern alternatives eventually.
How to make keydown behave consistently across browsers for printable characters?
The keydown event's key, code, and legacy properties like keyCode/which have long had cross-browser inconsistencies, especially with non-US keyboard layouts and special characters. Here are two better approaches:
1. Use event.key to target actual characters
Instead of relying on numerical key codes, check the event.key property directly—it returns the actual character that would be input (e.g., ; when you press that key, regardless of browser). You can filter for printable characters with a regex:
document.addEventListener('keydown', (e) => { // Match printable characters (letters, numbers, punctuation, symbols) const printableRegex = /^[\p{L}\p{N}\p{P}\p{S}]+$/u; if (printableRegex.test(e.key)) { console.log('Printable character:', e.key); // Handle the character here } });
This avoids the inconsistencies of keyCode and works across keyboards, since it targets the actual input character rather than the physical key code.
2. Use the input event (even better!)
If your goal is to capture characters as they're entered into a field (or the document), the input event is far more reliable. It triggers whenever content is added/changed—whether via keyboard, paste, or other input methods—and gives you direct access to the input data:
document.addEventListener('input', (e) => { if (e.data) { // e.data contains the exact character(s) that were added console.log('Input character:', e.data); } });
This method bypasses all keyboard event inconsistencies entirely, as it focuses on the result of the input rather than the key press itself. It’s the modern, recommended approach for capturing user input.
A note on legacy properties like keyCode
Properties like keyCode, which, and charCode are all deprecated, just like keypress. Trying to force consistent values across browsers for these is an uphill battle—they were never standardized properly in the first place. It’s much better to move to event.key or the input event instead.
内容的提问来源于stack exchange,提问作者Merouane




