48-键盘事件
Last updated
Last updated
<body>
<script>
document.onkeydown = function(event) {
event = event || window.event;
console.log('qianguyihao 键盘按下了');
};
document.onkeyup = function() {
console.log('qianguyihao 键盘松开了');
};
</script>
<input type="text" />
</body> <body>
<script>
document.onkeydown = function(event) {
event = event || window.event;
console.log('qianguyihao:键盘按下了');
// 判断y和ctrl是否同时被按下
if (event.ctrlKey && event.keyCode === 89) {
console.log('ctrl和y都被按下了');
}
};
</script>
</body> <body>
<input type="text" />
<script>
//获取input
var input = document.getElementsByTagName('input')[0];
input.onkeydown = function(event) {
event = event || window.event;
//console.log('qianguyihao:' + event.keyCode);
//数字 48 - 57
//使文本框中不能输入数字
if (event.keyCode >= 48 && event.keyCode <= 57) {
//在文本框中输入内容,属于onkeydown的默认行为
return false; // 如果在onkeydown中取消了默认行为,则输入的内容,不会出现在文本框中
}
};
</script>
</body><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
<style type="text/css">
#box1 {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div id="box1"></div>
<script type="text/javascript">
// 使div可以根据不同的方向键向不同的方向移动
/*
* 按左键,div向左移
* 按右键,div向右移
* ...
*/
//为document绑定一个按键按下的事件
document.onkeydown = function(event) {
event = event || window.event;
//定义一个变量,来表示移动的速度
var speed = 10;
//当用户按了ctrl以后,速度加快
if (event.ctrlKey) {
console.log('smyhvae ctrl');
speed = 20;
}
/*
* 37 左
* 38 上
* 39 右
* 40 下
*/
switch (event.keyCode) {
case 37:
//alert("向左"); left值减小
box1.style.left = box1.offsetLeft - speed + 'px'; // 在初始值的基础之上,减去 speed 大小
break;
case 39:
//alert("向右");
box1.style.left = box1.offsetLeft + speed + 'px';
break;
case 38:
//alert("向上");
box1.style.top = box1.offsetTop - speed + 'px';
break;
case 40:
//alert("向下");
box1.style.top = box1.offsetTop + speed + 'px';
break;
}
};
</script>
</body>
</html>