javascript alt 键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11412044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript alt key
提问by Riera
We are creating a web user interface that looks like a desktop window. Now we need to handle the Altkey. When Altkey is pressed the focus goes to the upper menu.
我们正在创建一个看起来像桌面窗口的 Web 用户界面。现在我们需要处理Alt密钥。当Alt按下 键时,焦点转到上层菜单。
In Javascript, how to get the event for Altkey when ONLY Altkey is pressed? I need to ensure that no other key was pressed at the same time.
在 Javascript 中,如何在按下AltONLYAlt键时获取键的事件?我需要确保没有同时按下其他键。
Thanks in advance.
提前致谢。
采纳答案by Riera
I don't know if this is the most elegant solution, but it worked fine.
我不知道这是否是最优雅的解决方案,但效果很好。
$(function()
{
//Flag to check if another key was pressed with alt
var vAnotherKeyWasPressed = false;
//ALT keycode const
var ALT_CODE = 18;
//When some key is pressed
$(window).keydown(function(event)
{
//Identifies the key
var vKey = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
//The last key pressed is alt or not?
vAnotherKeyWasPressed = vKey != ALT_CODE;
});
//When some key is left
$(window).keyup(function(event)
{
//Identifies the key
var vKey = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
//If the key left is ALT and no other key is pressed at the same time...
if (!vAnotherKeyWasPressed && vKey == ALT_CODE)
{
//Focus the menu
$('#myMenu').focus();
//Stop the events for the key to avoid windows set the focus to the browser toolbar
return false;
}
});
});
回答by Ricky
maybe like this
也许像这样
document.onkeydown = keydown;
function keydown(evt) {
if (!evt) evt = event;
if (evt.altKey) {
alert('alt');
}
} // function keydown(evt)?
回答by Talha
Working Demo
工作演示
document.onkeyup = KeyCheck;
function KeyCheck(e)
{
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID)
{
case 18:
document.Form1.KeyName.value = "Alt";
// do your work on alt key press....
break;
case 17:
document.Form1.KeyName.value = "Ctrl";
break;
}
}
And your html may be like that
你的 html 可能是这样的
<form name="Form1">
<input type="text" name="KeyName" value="" />
</form>?
Note:If you want to get the alt event on other control/type than modify it with your requirements.
注意:如果您想在其他控件/类型上获取 alt 事件而不是根据您的要求修改它。
回答by Jon Snow
just put e.preventDefault();
就放 e.preventDefault();
$(document).on('keydown', function (e) {
if (e.key === 'Alt') {
e.preventDefault();
}
});