Rie*_*era 10 javascript keyboard-events
我们正在创建一个看起来像桌面窗口的Web用户界面.现在我们需要处理Alt密钥.当Alt按下键焦点转到上一级菜单.
在Javascript中,Alt当Alt按下ONLY 键时如何获取键的事件?我需要确保没有同时按下其他键.
提前致谢.
小智 13
也许是这样的
document.onkeydown = keydown;
function keydown(evt) {
if (!evt) evt = event;
if (evt.altKey) {
alert('alt');
}
} // function keydown(evt)?
Run Code Online (Sandbox Code Playgroud)
工作演示
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;
}
}
Run Code Online (Sandbox Code Playgroud)
你的HTML可能就是这样
<form name="Form1">
<input type="text" name="KeyName" value="" />
</form>?
Run Code Online (Sandbox Code Playgroud)
注意:如果您想在其他控件/类型上获取alt事件,请根据您的要求修改它.
我不知道这是否是最优雅的解决方案,但效果很好。
$(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;
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24361 次 |
| 最近记录: |