键盘控制平滑运动

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>键盘控制平滑运动</title>
<style type="text/css">
.div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 120px;
left: 100px;
}
</style>
</head>
<body>
<div class="div"></div>
</body>
<script type="text/javascript">
var div = document.querySelector('.div');

// 能否向左|右|上|下运动
var l_able = false;
var t_able = false;
var r_able = false;
var b_able = false;
setInterval(function () {
// l_able为假,则后者短路,可以实现if的简写
l_able && (div.style.left = div.offsetLeft - 3 + 'px'); // 左
t_able && (div.style.top = div.offsetTop - 3 + 'px'); // 上
if (r_able == true) {
div.style.left = div.offsetLeft + 3 + 'px'; // 右
}
b_able && (div.style.top = div.offsetTop + 3 + 'px'); // 下

}, 16);

document.onkeydown = function (ev) {
switch(ev.keyCode) {
case 37: l_able = true; break;
case 38: t_able = true; break;
case 39: r_able = true; break;
case 40: b_able = true; break;
}
}

document.onkeyup = function (ev) {
console.log(ev);
switch(ev.keyCode) {
case 37: l_able = false; break;
case 38: t_able = false; break;
case 39: r_able = false; break;
case 40: b_able = false; break;
}
}
</script>
</html>

posted @ 2018-10-18 18:38  不沉之月  阅读(131)  评论(0编辑  收藏  举报