<!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>Document</title> <script> window.onload = function(){ console.log("test") document.getElementById('mess').onkeydown = function(e){ console.log(e.keyCode) console.log(e.target) if (e.keyCode == 16) { send(); } } } </script> </head> <body> <div style="height: 400px;">消息 </div> <div><input type="text" id="mess"> </input><button onclick="send()">发送消息</button></div> </body> </html>在此基础上要求要求实现点击shift键的时候将事件源和keyCode展示在输入框上方的div
时间: 2023-12-06 12:03:50 浏览: 108
好的,您可以按照以下代码进行修改:
```html
<!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>Document</title>
<script>
window.onload = function () {
console.log("test")
document.getElementById('mess').addEventListener('keydown', function (e) {
console.log(e.keyCode)
console.log(e.target)
if (e.keyCode == 16) {
showKeyCode(e);
}
});
}
function showKeyCode(event) {
var target = event.target;
var keyCode = event.keyCode;
var displayDiv = document.getElementById('display');
displayDiv.innerText = "事件源:" + target.tagName + ",keyCode:" + keyCode;
}
</script>
</head>
<body>
<div style="height: 400px;">消息</div>
<div>
<input type="text" id="mess">
<button onclick="send()">发送消息</button>
</div>
<div id="display"></div>
</body>
</html>
```
这段代码与您提供的代码类似,不过我将事件绑定到了输入框上,而不是整个文档。当按下 Shift 键时,会调用 `showKeyCode` 函数,该函数会获取事件源和 keyCode,并将其展示在 id 为 `display` 的 div 中。
阅读全文