javascript alt键 [英] javascript alt key

查看:110
本文介绍了javascript alt键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We are creating a web user interface that looks like a desktop window. Now we need to handle the Alt key. When Alt key is pressed the focus goes to the upper menu.

在Javascript中,如何获取 Alt的事件 Alt 键时kbd>键?我需要确保没有同时按下其他键。

In Javascript, how to get the event for Alt key when ONLY Alt key is pressed? I need to ensure that no other key was pressed at the same time.

提前致谢。

推荐答案

我不知道这是否是最优雅的解决方案,但它运行良好。

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

这篇关于javascript alt键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆