在javascript中获取按键

时间:2013-12-13 06:19:11

标签: javascript keyboard

我需要一些帮助来获得键盘按键。我想构建一个函数来返回当前按下的键。怎么可以这样做?

非常感谢。

2 个答案:

答案 0 :(得分:0)

是的,它可以完成,甚至您可以使用以下

做更多事情

http://www.openjs.com/scripts/events/keyboard_shortcuts/

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="./pages/scripts/jsl.js"></script>
<script type="text/javascript" src="./pages/scripts/common.js"></script>
<script type="text/javascript" src="./pages/scripts/shortcuts_v1.js"></script>
<script type="text/javascript">
function init() {
    shortcut("Shift+F1",function(event) {
        alert("Help Me!");
        event.preventDefault();
    });
    shortcut("Ctrl+S",function(event) {
        alert("Saved!");
        event.preventDefault();
    });
    shortcut("Right",function(event) {
        alert("Right");
        event.preventDefault();     
    });
}

addEvent(window,'load',init);
//ie workaround
document.onfocusout = function(e){
    if( e === undefined ){//ie
        var evt = event;//ie uses event
        if( evt.toElement == null ){//check where focus was lost to
            document.getElementById('status').innerHTML += "document.onfocusout->lost<br>";         
        }
    }
};

//ie workaround
document.onfocusin = function(e){
    if( e === undefined ){//ie
        var evt = event;//ie uses event
        if( evt.toElement == null ){//check where focus was lost to
            document.getElementById('status').innerHTML += "document.onfocusout->gained<br>";       
        }
    }
};

window.onblur = function(e){
 if( e !== undefined ){//ie will have an undefined e here, so this screens them out
     document.getElementById('status').innerHTML += "window.onblur->lost<br>";
 }
};

window.onfocus = function(e){
 if( e !== undefined ){//ie will have an undefined e here, so this screens them out
     document.getElementById('status').innerHTML += "window.onblur->gained<br>";
 }
};
</script>
</head>
<body>
<div id="status"></div>
</body>
</html>

答案 1 :(得分:0)