Js车剧本,我做错了什么?

时间:2015-05-10 19:58:45

标签: javascript html css

我尝试了一切来解决这个问题。我想在没有使用Canvas的情况下像汽车一样进行div移动,因为我不关心动画。

当我按WASD键时,问题是div或汽车实际上没有移动。有人能告诉我我做错了什么吗?

我只是希望它能够向上,向下,向左和向右移动。

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.grid{
    border:2px solid #333;
    width:800px;
    height:800px;
}

#box{
    background-color:DeepSkyBlue;
    width:50px;
    height:50px;
}
</style>
<script type="text/javascript">
window.onload=function()
{
   var car = document.getElementById("box");
   var carpos = car.getBoundingClientRect();
   var x = carpos.left;
   var y = carpos.right;

   car.addEventListener("keypress", keyBindOn(), false);
};

function keyBindOn(event)
{
    var code1 = event.keyCode;
    if(code1 == 87)
    {
        y -= 1;
    }

    if(code1 == 83)
    {
        y += 1;
    }

    if(code1 == 65)
    {
        x -= 1;
    }

    if(code1 == 68)
    {
        x += 1;
    }
}
</script>
</head>
<body>
<div class="grid"><div id="box" ></div></div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

JS:

的Onload:

var car = document.getElementById("box");
// Init these styles so on the event they exist and we can parse them for their integer values
car.style.top = '0px';
car.style.left = '0px';
// key events are attached to the document
document.addEventListener("keydown", keyBindOn, false);

关键功能:

function keyBindOn(event) {
    var car = document.getElementById("box");
    // These values will come back as strings (10px) so parsing them will get us integers
    var y = parseInt(car.style.top, 10);
    var x = parseInt(car.style.left, 10);
    var code1 = event.keyCode;
    // Switch is much better than if here because it can be only one case each time.
    // Your original if would check against every value even when we had already found the one that matched.
    // This checks WASD and arrows
    switch (code1) {
        case 65:
        case 37:
            x -= 2;
            break;
        case 87:
        case 38:
            y -= 2;
            break;
        case 68:
        case 39:
            x += 2;
            break;
        case 83:
        case 40:
            y += 2;
            break;
    }

    // Reset the new styles
    car.style.top = y + 'px';
    car.style.left = x + 'px';
}

小提琴:http://jsfiddle.net/5h4215aj/2/

这可以大大改进,但它应该让你开始。我做得很快。还有很大的改进空间,但我希望这可以帮助您开始。我大多只修复了你的代码中的问题,并在“car”上进行了一些粗略的初始化,以确保get get中存在内联样式,以便关键功能起作用。

编辑:甚至没有意识到这个问题是5个月大。 oops =]