<!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>
<style>
*{margin: 0; padding: 0;}
#box1{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 0px;
left: 0px;
}
</style>
</head>
<body>
<div id="box1">
</div>
<script>
window.onload = function() {
// 按键信息
document.onkeypress = (e) => {
e = e || window.event
console.log(e.keyCode)
console.log(e.which) // 低版本
console.log('onkeypress');
}
document.onkeydown = (e) => {
e = e || window.event
console.log('onkeydown');
}
// keydown和keypress的区别
// 相同点:常规键按下都会触发
// 不同点:
// 1-按下esc,onkeydown触发;onkeypress不会
// 2-keydown 按下字母键,只能获取字母键大写的键码
}
</script>
</body>
</html>
JS中的按键信息,keydown和keypress的区别
最新推荐文章于 2023-07-09 20:09:26 发布