键盘事件
html部分
<div class="insert">
<div class="key">
请按下你的键盘
</div>
</div>
css部分
* {
margin: 0;
padding: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
overflow: hidden;
}
.insert{
display: flex;
gap: 10px;
}
.key {
border: 1px solid #eee;
box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.4),
6px 0 10px -5px rgba(0, 0, 0, 0.4);
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
font-size: 20px;
font-weight: bold;
min-width: 150px;
position: relative;
}
.key small{
position: absolute;
top: -40px;
}
js部分
// 获取dom对象
const insert = document.querySelector('.insert');
// 绑定全局键盘事件
window.addEventListener("keydown", (e) => {
// 插入dom文本
insert.innerHTML = `
<div class="key">
${e.key === ' ' ? 'Space' : e.key}
<small>event.key</small>
</div>
<div class="key">
${e.keyCode}
<small>event.keyCode</small>
</div>
<div class="key">
${e.code}
<small>event.code</small>
</div>
`;
})
效果