<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#box{width: 100px;height: 100px;border-radius: 50%;background: red;position: absolute;left: 0;top: 0;}
</style>
</head>
<body>
<div id="box"></div>
<script type="text/javascript">
/*
onkeydown onkeypress onkeyup
keyCode :键码
点击上下左右 实现小球向对应方向移动
*/
var o=document.getElementById('box');
document.onkeydown=function (e) {
e=e||window.event;
console.log(e);
switch(e.keyCode){
case 37:
// console.log('左');
moveHor(-10);
break;
case 38:
// console.log('上');
moveVer(-10);
break;
case 39:
// console.log('右');
moveHor(10);
break;
case 40:
// console.log('下');
moveVer(10);
break;
default:
console.log('其他');
break;
}
};
function moveHor(speed){
o.style.left=o.offsetLeft+speed+'px';
}
function moveVer(speed){
o.style.top=o.offsetTop+speed+'px';
}
</script>
</body>
</html>
JS中的键盘事件
猜你喜欢
转载自blog.csdn.net/weixin_44606660/article/details/87779786
今日推荐
周排行