<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Event KeyCodes</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div id="insert">
    <div class="key">
      Press Any Key to get the KeyCode
    </div>
  </div>

  <script src="script.js"></script>
</body>
</html>
*{
  box-sizing: border-box;
}

body{
  background-color: #e1e1e1;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
}

.key{
  border: 1px solid #999;
  background-color: #eee;
  box-shadow: 1px 1px 3px rgba(0,0,0,0.1);
  display: inline-flex;
  font-size: 20px;
  font-weight: bold;
  padding: 20px;
  flex-direction: column;
  margin: 10px;
  min-width: 150px;
  position: relative;
  text-align: center;
}

.key small{
  position: absolute;
  top: -24px;
  left: 0;
  text-align: center;
  width: 100%;
  color: #555;
  font-size: 14px;
}

const insert = document.getElementById('insert')

window.addEventListener('keydown', (event) => {
  insert.innerHTML = `
  <div class="key">
  ${event.key === ' ' ? 'Space' : event.key} 
  <small>event.key</small>
  </div>

  <div class="key">
  ${event.keyCode}
  <small>event.keyCode</small>
  </div>

  <div class="key">
  ${event.code}
  <small>event.code</small>
  </div>
  `
})

结果如下:
dsgdfghhjghjgerebc20220616105144

Q.E.D.


一个二次元web开发咸鱼