以下代码应该从箭头中为html元素创建一个控制器。
moveDown()
函数应该检查汽车是否向上移动并停止移动并使其向下移动并且moveUp()
应该执行相同的过程但是要将其向上移动;
问题是moveDown()
和moveUp()
工作不正常,你能帮助我吗?
谢谢!
<!DOCTYPE html>
<html>
<body >
<p id="demo">A function is triggered when the user is pressing a key in the input field.</p>
<input type="text" id="car" style="position:relative;">
<script>
document.addEventListener("keydown", myFunction);
var left=0;
var interval=0;
var down=0;
var up=0;
function myFunction(e) {
var car=document.getElementById("car");
//Move Right
if(e.keyCode == 39){ moveRight(car);}
//Stop Move
if(e.keyCode == 37){stopMove(car);}
//Move down
if(e.keyCode ==40){moveDown(car)};
//Move Up
if(e.keyCode==38){moveUp(car)};
}
//Move the car
function moveRight(car){
//Check if the car is not already moving
if(interval==0){
interval=window.setInterval(function(){
left+=2;
car.style.left=left+"px";},
30);}
}
//Stop Move
function stopMove(car){
clearInterval(interval);
//Reset the interval to 0
interval=0;}
//Move down
function moveUp(car){
interval=window.setInterval(function(){
down+=2;
car.style.bottom=down+"px";
},30);
}
//Move up
function moveDown(car){
interval=window.setInterval(function(){
down+=2;
car.style.bottom=-down+"px";
},30);
}
</script>
</body>
</html>