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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。