按下 ALT 键时如何在 Javascript 中进行检测?

新手上路,请多包涵

我们正在创建一个看起来像桌面窗口的网络用户界面。现在我们需要处理 Alt 键。当 按下 Alt 键时,焦点转到上层菜单。

在 Javascript 中,如何在仅 按下 Alt 键时获取 Alt 键的事件?

我需要确保没有同时按下其他键。

原文由 Riera 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 497
2 个回答

我不知道这是否是最优雅的解决方案,但效果很好。

 $(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;
        }
    });
});

原文由 Riera 发布,翻译遵循 CC BY-SA 3.0 许可协议

也许像这样

 document.onkeydown = keydown;

function keydown(evt) {
    if (!evt) evt = event;
    if (evt.altKey) {
        console.log('alt');
    }
} // function keydown(evt)​
 <input type"text" onkeydown="keydown" />

原文由 Ricky 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题