html,,,,,移动小坦克,, #tank {, position: absolute;, width: 50px;, height: 50px;, backgroundimage: url('tank.png');, },,,,,, let tank = document.getElementById('tank');, let x = 0, y = 0;, document.onkeydown = (e) => {, switch (e.keyCode) {, case 37:, x = 10;, break;, case 38:, y = 10;, break;, case 39:, x += 10;, break;, case 40:, y += 10;, break;, }, tank.style.left = x + 'px';, tank.style.top = y + 'px';, };,,,,
``<meta charset="UTF8">
<title>移动的小坦克示例</title>
<style>
#gameArea {
position: relative;
width: 600px;
height: 400px;
border: 1px solid black;
overflow: hidden;
}
.tank {
position: absolute;
width: 50px;
height: 50px;
backgroundcolor: green;
transition: left 0.2s, top 0.2s;
}
</style>
<div id="gameArea">
<div class="tank" id="playerTank"></div>
</div>
<script>
var playerTank = document.getElementById('playerTank');
var gameArea = document.getElementById('gameArea');
var speed = 5; // 坦克移动速度
var moveLeft = false;
var moveRight = false;
var moveUp = false;
var moveDown = false;
function moveTank() {
var currentLeft = parseInt(playerTank.style.left) || 0;
var currentTop = parseInt(playerTank.style.top) || 0;
if (moveLeft && currentLeft > 0) {
playerTank.style.left = (currentLeft speed) + 'px';
} else if (moveRight && currentLeft < gameArea.offsetWidth playerTank.offsetWidth) {
playerTank.style.left = (currentLeft + speed) + 'px';
}
if (moveUp && currentTop > 0) {
playerTank.style.top = (currentTop speed) + 'px';
} else if (moveDown && currentTop < gameArea.offsetHeight playerTank.offsetHeight) {
playerTank.style.top = (currentTop + speed) + 'px';
}
}
document.addEventListener('keydown', function(event) {
switch (event.keyCode) {
case 37: // 左箭头键
moveLeft = true;
break;
case 38: // 上箭头键
moveUp = true;
break;
case 39: // 右箭头键
moveRight = true;
break;
case 40: // 下箭头键
moveDown = true;
break;
}
});
document.addEventListener('keyup', function(event) {
switch (event.keyCode) {
case 37: // 左箭头键
moveLeft = false;
break;
case 38: // 上箭头键
moveUp = false;
break;
case 39: // 右箭头键
moveRight = false;
break;
case 40: // 下箭头键
moveDown = false;
break;
}
});
setInterval(moveTank, 20); // 每20毫秒调用一次moveTank函数,实现坦克的平滑移动
</script>
```html
```
在这个示例中,我们创建了一个`div`元素作为坦克的容器,并通过CSS样式定义了坦克的外观,坦克的移动是通过监听键盘的`keydown`事件来实现的,根据按下的箭头键来改变坦克的位置,当用户按下箭头键时,坦克会在相应的方向上移动10像素。