按键事件
onkeydown //键盘按下
onkeypress //键盘按下(除去功能键,如:Esc,Shift,Ctrl…)
onkeyup //键盘弹起
例子:
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="text" name="username" id="username" value="" />
<script type="text/javascript">
var inputDom=document.querySelector('#username')
var showCodeDiv=document.createElement("div");
showCodeDiv.style.width="200px"
showCodeDiv.style.height="200px"
showCodeDiv.style.backgroundColor="rgba(0,0,0,0.6)"
showCodeDiv.style.position="fixed"
showCodeDiv.style.left="calc(50% - 100px)"//注意空格
showCodeDiv.style.top="calc(50% - 100px)"
showCodeDiv.style.textAlign="center"
showCodeDiv.style.lineHeight="200px"
showCodeDiv.style.fontSize="80px"
document.body.appendChild(showCodeDiv)
//键盘按下事件
inputDom.onkeydown=function(event){
console.log(event);
showCodeDiv.innerHTML=event.key
}
//键盘按下事件
inputDom.onkeypress=function(event){
console.log(event);
}
//键盘弹起事件
inputDom.onkeyup=function(event){
console.log(event);
}
</script>
</body>
结果:
打字小游戏的例子:
随机给出字母识别打字是否正确
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#showCode{
width: 200px;
height: 200px;
font-size: 80px;
color: #fff;
line-height: 200px;
text-align: center;
position: fixed;
left: calc(50% - 100px);
top: 200px;
background-color: rgba(0,0,0,0.6);
}
</style>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script src="js/alert.js" type="text/javascript"></script>
</head>
<body>
<div id="showCode"></div>
<script type="text/javascript">
var score=0;
function randomCode(){
var randomNum=97+parseInt(Math.random()*26);
var randomStr=String.fromCharCode(randomNum);
var ucStr=randomStr.toUpperCase()
var showCodeDiv=document.querySelector("#showCode")
showCodeDiv.innerHTML=ucStr
}
randomCode();
var body=document.body
body.onkeypress=function(event){
var keyCode=event.key.toUpperCase()
var showCodeDiv=document.querySelector("#showCode")
if(keyCode==showCodeDiv.innerHTML){
console.log("打字正确,得分+1")
score++;
randomCode();
}
}
var fn10=function(){
alert("您每分钟能敲"+score*6+"个字母");
}
setTimeout(fn10,10000)
</script>
</body>
</html>
结果: