[英]addEventListener isn't triggering on keypress
I'm trying to add custom keys to trigger events. 我正在尝试添加自定义键来触发事件。 I can get the
keyup
and the keydown
events to work but for some reason the keypress
event isn't working. 我可以使
keyup
和keydown
事件正常工作,但是由于某些原因, keypress
事件无法正常工作。 I have seen many duplicates to these but most is in jquery. 我见过很多重复的东西,但大多数在jquery中。
In addition, in researching this, I came across the documentation that states that keyCode
is deprecated and key
should be used instead. 另外,在研究此问题时,我遇到了说明
keyCode
已弃用的文档,应改为使用key
。 However if I write 但是如果我写
if (event.key === 74)
the code doesn't work 代码不起作用
The code below is a simple example of what i'm trying to do. 下面的代码是我正在尝试做的一个简单示例。
window.addEventListener('keypress', function(event) { if (event.keyCode === 74) { console.log('Show me'); } });
Your code works just fine (assuming you are entering a capital J
). 您的代码工作正常(假设您输入的是大写
J
)。
If you also want to check against a lowercase J
, the keyCode would be 106
: 如果您还想检查小写的
J
,则keyCode将为106
:
window.addEventListener('keypress', function(event) { if (event.keyCode === 74 || event.keyCode === 106) { console.log('Show me'); } });
The difference is in the capital and small j. 区别在于大写字母和小j。 You are using code for capital j only
您仅将代码用于大写j
window.addEventListener('keypress', function(event) { console.log(event.keyCode) if (event.keyCode === 74 || event.keyCode === 106) { console.log('Show me'); } });
You need to use the even.which when you check for J(74): 当您检查J(74)时,您需要使用even.which:
window.addEventListener('keypress', function(event) { if (event.which === 74) { console.log('Show me'); } });
You can use key down instead, this will catch both upper and lower case j
. 您可以改用key down,这将同时捕获大小写
j
。
window.addEventListener('keydown', function(event) { if (event.keyCode === 74) { console.log('Show me'); } });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.