原生js 小球随键盘移动事件小案例
1效果图2html和js3css4总结
1效果图
2html和js
<body>
<div id="ball"></div>
<script>
var ball = document.getElementById('ball');
var step = 2;
var run = false;
var runing;
window.onkeydown = function(e){
switch(e.keyCode){
case 37:
moveLeft();
break;
case 38:
moveTop();
break;
case 39:
moveRight();
break;
case 40:
moveBottom();
break;
}
}
window.onkeyup = function(){
clearInterval(runing);
run = false;
}
function moveLeft(){
if(run){
return;
}
runing = setInterval(function(){
run = true;
var l = ball.offsetLeft;
ball.style.left = (l - step)+'px';
},10);
}
function moveRight(){
if(run){
return;
}
runing = setInterval(function(){
run = true;
var l = ball.offsetLeft;
ball.style.left = (l + step)+'px';
},10);
}
function moveTop(){
if(run){
return;
}
runing = setInterval(function(){
run = true;
var t = ball.offsetTop;
ball.style.top = (t-step)+'px';
},10);
}
function moveBottom(){
if(run){
return;
}
runing = setInterval(function(){
run = true;
var t = ball.offsetTop;
ball.style.top = (t+step)+'px';
},10);
}
</script>
</body>
3css
<head>
<meta charset="UTF-8">
<title>上下左右</title>
<style>
* {
margin: 0px
;
padding: 0px
;
}
#ball {
width: 100px
;
height: 100px
;
background: purple
;
border-radius: 50px
;
position: absolute
;
}
</style>
</head>
4总结
点击小键盘的上线左右 可移动小球
转载请注明原文地址:https://blackberry.8miu.com/read-8734.html