<分区>
我正在制作一个程序,让用户移动汽车图像以避免图像上向下移动的障碍物。我可以上下左右移动汽车。我究竟该如何防止图像离开我创建的框?
我还移动了图像位置,使其看起来正好在边界处。有没有更简单的方法让它与盒子对齐?
//init object globally
var objImage = null;
function init() {
objImage = document.getElementById("car");
objImage.style.position = 'relative';
objImage.style.left = '748px';
objImage.style.top = '-405px';
}
function getKeyAndMove(e) {
var key_code = e.which || e.keyCode;
if (key_code == 37) {
moveLeft();
} else if (key_code == 38) {
moveUp();
} else if (key_code == 39) {
moveRight();
} else if (key_code == 40) {
moveDown();
}
}
function moveLeft() {
objImage.style.left = parseInt(objImage.style.left) - 5 + 'px';
}
function moveUp() {
objImage.style.top = parseInt(objImage.style.top) - 5 + 'px';
}
function moveRight() {
objImage.style.left = parseInt(objImage.style.left) + 5 + 'px';
}
function moveDown() {
objImage.style.top = parseInt(objImage.style.top) + 5 + 'px';
}
window.onload = init;
h1 {
font-size: 2.8em;
text-align: center;
}
#Screen {
border: 2px solid white;
width: 400px;
height: 400px;
padding-left: 0;
padding-right: 0;
margin-left: auto;
margin-right: auto;
display: block;
box-shadow: 0 0 20px gray;
}
#car {
width: 50px;
height: 120px;
}
<div onkeydown='getKeyAndMove(event)'>
<h1>Drive your car with arrow keys</h1>
<div id="Screen" width="400px" height="400px"></div>
<img id="car" tabindex="0" src='https://via.placeholder.com/120'>
</div>