HTML中的keyboardEvent代碼屬性表示鍵盤上的物理鍵。它用於返回觸發事件的鍵。
用法:
event.code
返回值:它返回一個代表按下哪個鍵的字符串。
範例1:帶KeyDown事件
<html>
<head>
<title>DOM keyboardEvent code Property</title>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h2>
DOM keyboardEvent code Property
</h2>
Input:
<input type="text" placeholder="Press any key..">
<p id="p"></p>
<script>
// Adding a event listener function
window.addEventListener("keydown", function(event) {
var code = "keydown code = '" +
event.code + "'" + "<br/>";
// Creating a span element
var element = document.createElement("span");
element.innerHTML = code;
// Appending the created element to paragraph
document.getElementById("p").appendChild(element);
}, true);
</script>
</body>
</html>
輸出:
範例2:帶有KeyPress事件
<html>
<head>
<title>DOM keyboardEvent code Property</title>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h2>
DOM keyboardEvent code Property
</h2>
Input:
<input type="text" placeholder="Press any key..">
<p id="p"></p>
<script>
// Adding a event listener function
window.addEventListener("keypress", function(event) {
var code = "keypress code = '" +
event.code + "'" + "<br/>";
// Creating a span element
var element = document.createElement("span");
element.innerHTML = code;
// Appending the created element to paragraph
document.getElementById("p").appendChild(element);
}, true);
</script>
</body>
</html>
輸出:
範例3:帶KeyUp事件
<html>
<head>
<title>DOM keyboardEvent code Property</title>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h2>
DOM keyboardEvent code Property
</h2>
Input:
<input type="text" placeholder="Press any key..">
<p id="p"></p>
<script>
// Adding a event listener function
window.addEventListener("keyup", function(event) {
var code = "keyup code = '" +
event.code + "'" + "<br/>";
// Creating a span element
var element = document.createElement("span");
element.innerHTML = code;
// Appending the created element to paragraph
document.getElementById("p").appendChild(element);
}, true);
</script>
</body>
</html>
輸出:
支持的瀏覽器:下麵列出了keyboardEvent代碼屬性支持的瀏覽器:
- 蘋果Safari 10.0
- 穀歌瀏覽器48.0
- Firefox 32.0
- Opera
- Internet Explorer不支持
相關用法
- HTML KeyboardEvent which用法及代碼示例
- HTML KeyboardEvent key用法及代碼示例
- HTML KeyboardEvent location用法及代碼示例
- HTML keyboardEvent charCode用法及代碼示例
- HTML KeyboardEvent keyCode用法及代碼示例
- HTML KeyboardEvent shiftKey用法及代碼示例
- HTML KeyboardEvent altKey用法及代碼示例
- HTML KeyboardEvent metaKey用法及代碼示例
- HTML DOM KeyboardEvent getModifierState()用法及代碼示例
- HTML <code>用法及代碼示例
- HTML DOM Code用法及代碼示例
- HTML <applet> code屬性用法及代碼示例
- HTML li value用法及代碼示例
注:本文由純淨天空篩選整理自Vishal Chaudhary 2大神的英文原創作品 HTML | DOM KeyboardEvent code Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。