<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 先给div一个简单的样式 */
div{
width: 400px;
height: 400px;
color: pink;
background: rgba(0,0,0,0.4);
text-align: center;
line-height: 400px;
font-size: 280px;
position: fixed;
top:calc( 50% - 200px);
left:calc( 50% - 200px);
}
</style>
</head>
<body>
<div> </div>
<script>
// 封装函数
function randomWord(){
// 一 先随机生成大写字母在ASCII码表中对应的十进制数
var randomNum = 65 + parseInt(Math.random()*26);
// 二 用函数 String.fromCharCode() 生成对应的随机字母
// String.fromCharCode()函数用于从一些Unicode字符值中返回一个字符串
var randomCode = String.fromCharCode(randomNum);
// 三 获取标签对象 div 并将随机生成的大写字母写入到此标签中
var oDiv = document.querySelector('div');
oDiv.innerHTML = randomCode ;
}
randomWord();
// 四 对 文档doucument 进行事件 类型为 kyedown 点击键盘事件绑定
document.addEventListener('keydown',function(e){
var oDiv = document.querySelector('div');
// 进行if条件判断 条件满足 键盘点击的字母与随机生成字母一直即可
if(e.key.toUpperCase() === oDiv.innerHTML){
randomWord();
}
})
// @码上成功~
</script>
</body>
</html>