键盘
开发工具与关键技术:DW
作者:冯超
撰写时间:2019年4月5日
keydown 表示按下键盘
keypress 表示按下键盘
keyup 表示键盘弹起
这三者的区别分别表现在发生的 先后顺序,获取到的键盘按钮值,已经对输入框的文本取值这三方面
先后顺序: 按照 keydown keypress keyup 顺序发生
键盘按钮值:
通过event对象的which属性获取键盘的值
keydown和keyup 能获取所有按键,不能识别大小写
keypress 不能获取功能键,如F1 SHIFT等,能够识别大小写
文本取值:
keydown和keypress:不能获取最后一个字符
keyup: 获取所有字符发生的先后顺序是 keydown,keypress,keyup
源代码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>键盘</title>
<script src="../jquery-1.12.4/jquery-1.12.4.min.js"></script>
</head>
<body>
<script>
var order = 0;
var clearTimer=null;
$(function(){
$("#i").keydown(function(e){
var selector = "keydown";
show(selector,e,$(this).val());
});
$("#i").keypress(function(e){
var selector = "keypress";
show(selector,e,$(this).val());
});
$("#i").keyup(function(e){
var selector = "keyup";
show(selector,e,$(this).val());
});
});
function show(selector,e,inputvalue){
clearTimeout(clearTimer);
action(selector);
key(selector,e);
value(selector,inputvalue);
clearTimer= setTimeout(clear,4000);
}
function action(selector){
$("#"+selector+"Action").css("background-color","yellow");
$("#"+selector+"Action").html("顺序: " + (++order ) );
}
function value(selector,value){
$("#"+selector+"Value").html(value);
}
function key(selector,e){
$("#"+selector+"Key").html(e.which);
}
function clear(){
order = 0;
$("tr#action div").css("","");
$("tr div").html("");
}
</script>
<style>
tr#action div{
border: 1px solid black;
height:50px;
background-color:silver;
}
tr#value div,tr#key div{
height:50px;
background-color:#d1d1d1;
}
td{
width:25%;
}
</style>
输入框:<input id="i">
<table width="100%">
<tr>
<td></td>
<td>keydown</td>
<td>keypress</td>
<td>keyup</td>
</tr>
<tr id="action">
<td>行为</td>
<td><div id="keydownAction"></div></td>
<td><div id="keypressAction"></div></td>
<td><div id="keyupAction"></div></td>
</tr>
<tr id="key">
<td>按键</td>
<td><div id="keydownKey"></div></td>
<td><div id="keypressKey"></div></td>
<td><div id="keyupKey"></div></td>
</tr>
<tr id="value">
<td>取值</td>
<td><div id="keydownValue"></div></td>
<td><div id="keypressValue"></div></td>
<td><div id="keyupValue"></div></td>
</tr>
</table>
</body>
</html>