为什么keypress事件检测到的大写字母显示为小写?

南宫思晨 阅读 26

我给输入框绑定了keypress事件,想记录用户输入的每个字符。但发现当按下Shift+字母键时(比如Shift+A),event.key返回的始终是小写字母”a”,而不是预期的大写”A”。这该怎么正确获取用户实际输入的字符?

尝试过用event.keyCode,但发现不同浏览器返回值差异大。也试过结合event.shiftKey判断,但感觉逻辑复杂容易出错。有没有更简洁的办法?

代码片段类似这样:

  
document.querySelector('input').addEventListener('keypress', function(e) {  
  console.log('输入字符:', e.key); // Shift+A时输出a  
});  

我来解答 赞 4 收藏
二维码
手机扫码查看
2 条解答
a'ゞ若惜
问题在于keypress事件在某些浏览器中会返回按键的“字符值”而不是实际输入的大小写。应该改用input或keydown事件配合event.key,它能正确反映大小写。直接换成这个:

document.querySelector('input').addEventListener('input', function(e) {
console.log('输入字符:', e.data); // 输入大写A就输出A
});


或者保持监听keydown,但用e.key就行:

document.querySelector('input').addEventListener('keydown', function(e) {
console.log('输入字符:', e.key);
});
点赞 2
2026-02-12 12:05
小东宇
小东宇 Lv1
我之前也遇到过。keypress已经废弃了,改用input事件或者keyup/keydown配合e.key就行,shift+字母自然就大写了。

直接这么写:

document.querySelector('input').addEventListener('input', function(e) {
console.log('输入字符:', e.data);
});


或者用keydown:

document.querySelector('input').addEventListener('keydown', function(e) {
console.log('输入字符:', e.key);
});


别再用keypress了,这玩意对大小写处理本来就有坑。
点赞 4
2026-02-09 14:22