div移动和发射子弹,案例如下
最开始时,方向键可移动
按下空格发射一颗子弹
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>键盘事件和组合键</title>
<style>
* {
margin: 0;
padding: 0;
}
#div1 {
width: 40px;
height: 40px;
position: absolute;
background: orange;
transform: rotate(0deg);
}
.zidan {
width: 5px;
height: 15px;
border-radius: 50%;
position: absolute;
background: #f06;
}
</style>
</head>
<body>
<div id="div1" style="top:350px;left:100px"></div>
</body>
</html>
<script src="../common.js"></script>
<script>
//要求 : 按住键盘的上下左右箭头 控制div的移动
// 按住 空格键 创建子弹 并发射子弹
//37 39 32
let $div1 = $('#div1');
document.onkeydown = function (e) {
e = e || window.event;
let code = e.keyCode || e.which || e.charCode;
// console.log(1);
// console.log(code);
switch (code) {
case 37:
$div1.style.left = parseInt(div1.style.left) - 10 + "px";
console.log($div1.style.left);
break;
case 38:
$div1.style.top = parseInt(div1.style.top) - 10 + "px";
break;
case 39:
$div1.style.left = parseInt(div1.style.left) + 10 + "px";
break;
case 40:
$div1.style.top = parseInt(div1.style.top) + 10 + "px";
break;
case 32:
//创建子弹
let $div = document.createElement('div');
document.body.appendChild($div);
$div.className = 'zidan';
//子弹初始位置
let x = parseInt($div1.style.left) + 20;
let y = parseInt($div1.style.top) - 15;
$div.style.left = x + 'px';
$div.style.top = y + 'px';
// console.log(x,y);
//发射
let timer = setInterval(() => {
$div.style.top = parseInt($div.style.top) - 10 + 'px';
if(parseInt($div.style.top) < 15){
$div.remove();
clearInterval(timer);
}
}, 10);
break;
default:
console.log("请按上下左右键");
break;
}
}
</script>