javascript - 检测按下或向上按下 ctrl 键,按键事件不会触发
我在这里看到一些类似的问题(例如JavaScript:检查是否按下了CTRL按钮)但我的问题实际上是事件触发。我的 js 代码:
// Listen to keyboard.
window.onkeypress = listenToTheKey;
window.onkeyup = listenToKeyUp;
/*
Gets the key pressed and send a request to the associated function
@input key
*/
function listenToTheKey(e)
{
if (editFlag == 0)
{
// If delete key is pressed calls delete
if (e.keyCode == 46)
deleteNode();
// If insert key is pressed calls add blank
if (e.keyCode == 45)
createBlank();
if (e.keyCode == 17)
ctrlFlag = 1;
}
}
除 ctrl 之外的任何其他键都会触发该事件。
我还需要通过 ctrl 触发它。
我不能使用 jQuery/原型/任何东西,所以这些解决方案是不可接受的。
那么...我怎样才能检测到ctrl?
I see some similar questions here (like JavaScript: Check if CTRL button was pressed) but my problem is actually the event triggering. My js code:
// Listen to keyboard.
window.onkeypress = listenToTheKey;
window.onkeyup = listenToKeyUp;
/*
Gets the key pressed and send a request to the associated function
@input key
*/
function listenToTheKey(e)
{
if (editFlag == 0)
{
// If delete key is pressed calls delete
if (e.keyCode == 46)
deleteNode();
// If insert key is pressed calls add blank
if (e.keyCode == 45)
createBlank();
if (e.keyCode == 17)
ctrlFlag = 1;
}
}
The event triggers for any other keys except the ctrl.
I need to also trigger it for ctrl.
I can't use jQuery/prototype/whatever so those solutions are not acceptable.
So... how can I detect the ctrl?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试使用
if (e.ctrlKey)
。MDN:event.ctrlKey
Try using
if (e.ctrlKey)
.MDN: event.ctrlKey
使用 onkeydown 而不是 onkeypress 可能会有所帮助。
来自 http://www.w3schools.com/jsref/event_onkeypress.asp
Using onkeydown rather than onkeypress may help.
From http://www.w3schools.com/jsref/event_onkeypress.asp
您的事件有一个名为 ctrlKey 的属性。您可以检查此项以查看该键是否被按下。有关更多控制(如按键)的信息,请参阅下面的代码片段。
Your event has a property named ctrlKey. You can check this to look if the key was pressed or not. See snippet below for more control like keys.
这基本上是 Rick Hoving 的答案,但它使用
keydown
就像 Danielle Cerisier 建议的那样Please note that you may have to click inside the preview box to focus before pressing ctrl
This is basically Rick Hoving's answer, but it uses
keydown
like Danielle Cerisier suggestsPlease note that you may have to click inside the preview box to focus before pressing ctrl