js中的键盘事件 和一些简单应用
onkeydown, onkeyup
键盘事件一般都是对可获得焦点的对象 例如input
下面是一些应用
一、
在文本框中只能输入非数字的元素
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
window.onload = function(){
document.onkeydown = function(event){
event = event || window.event;
// console.log(event.keyCode);
if(event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode >= 96 && event.keyCode <= 105) //设置只能输入非数字 用编码判断
return false;
}
}
</script>
</head>
<body>
<input type="text" name="" id="" value="" />
</body>
</html>
二、
使用上下左右移动盒子并按着ctrl加速
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#box{
width: 100px;
height: 100px;
background-color: aqua;
position: absolute; /* 定位很重要 */
}
</style>
<script type="text/javascript">
window.onload = function(){
var box = document.getElementById("box");
event = event || window.event;
document.onkeydown = function(event){
var speed = 10;
if(event.ctrlKey){
speed = 50; //改变移动速度
}
// 37左
// 38下
// 39右
// 40下
switch(event.keyCode){
case 37: box.style.left = box.offsetLeft - speed + "px"; break;
case 38: box.style.top = box.offsetTop - speed + "px"; break;
case 39: box.style.left = box.offsetLeft + speed + "px"; break;
case 40: box.style.top = box.offsetTop + speed + "px"; break;
}
}
}
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>
此方法有一点问题 盒子移动的第一次和的二次之间会有明显的小卡顿 这个问题 需要用到其他知识解决 这里暂不解决 可以参考后续发布