<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{padding: 0;margin: 0;}
#box{width: 100px;height: 100px;background-color: red;position: absolute;
border-radius: 50%;top: 100px;}
</style>
</head>
<body>
<div id="box"></div>
<script type="text/javascript">
/*
1.用键盘实现小球向上下左右四个方向移动
*/
var o=document.querySelector('#box');
var speed=5;
document.onkeydown=function (e) {
e=e||window.event;
//判断用户按了哪个键
// console.log(e.keyCode);
switch(e.keyCode){
case 37:
moveHor(-speed);//左
break;
case 38:
moveVer(-speed);//上
break;
case 39:
moveHor(speed);//右
break;
case 40:
moveVer(speed);//下
break;
default:
console.log('点击了其他按钮');
break;
}
};
// function moveLeft(){
// o.style.left=o.offsetLeft-5+'px';
// }
// function moveRight(){
// o.style.left=o.offsetLeft+5+'px';
// }
//水平移动
function moveHor(speed){
o.style.left=o.offsetLeft+speed+'px';
}
function moveVer(speed){
o.style.top=o.offsetTop+speed+'px';
}
</script>
</body>
</html>
javascript制作键盘控制圆的移动效果
猜你喜欢
转载自blog.csdn.net/weixin_44830974/article/details/90018460
今日推荐
周排行