先看一段示例代码,在不同浏览器中的行为
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script>
$(document).ready(function(){
$("#test").keydown(function(){
console.log("jquery_keydown"+event.keyCode);
});
$("#test").keypress(function(anything){
console.log("jquery_keypress:"+anything.key);
});
$("#test").keyup(function(event){
console.log("jquery_keyup"+event.keyCode);
});
});
</script>
</head>
<body>
<button onkeyup="up(event)" onkeydown="down()" onkeypress="press(event)">Test</button>
<input id="test" type="text">
<script>
function up(e){
console.log("up:"+e.key);
}
function down(){
console.log("down:"+event.key);
}
function press(e){
console.log("press:"+e.keyCode);
}
</script>
</body>
</html>
结论
“keyup,keydown” returns Character codes (A number which represents an ASCII character)
“keypress” returns Key codes (A number which represents an actual key on the keyboardTo find out if the user is pressing a printable key (e.g. “a” or “5”), it is recommended to use this property on the onkeypress event. To find out if the user is pressing a function key (e.g. “F1”, “CAPS LOCK” or “Home”) use the onkeydown or onkeyup event.
功能键建议用 keyup, keydown; 可打印出字的键建议用 keypressIn Firefox, the keyCode property does not work on the onkeypress event (will only return 0). For a cross-browser solution, use the which property together with keyCode event.which || event.keyCode
Firefox下用 keypress 函数 event.keyCode会返回 0 (IE8 以前不支持event.keywhich)Both the keyCode and which property is provided for compatibility only. The latest version of the DOM Events Specification recommend using the key property instead
最新的DOM Events能用key把字母打出来If you want to find out whether the “ALT”, “CTRL”, “META” or “SHIFT” key was pressed when a key event occured, use the altKey, ctrlKey, metaKey or shiftKey property.
还有这些关键词可以用如果判断功能键jquery里function第一个参数默认就是 event, 所以给什么变量都行