2

我想移动我使用向左箭头创建的板向左移动,向右箭头向右移动。但我不知道如何用语法写左/右箭头,所以我只使用'a'和'd'来左右移动(就像在反击中一样)。有人可以帮我吗?这是我的代码

function moveObj(name, Xpix) 
{    
    obj = document.getElementById(name);

    px = parseInt(obj.style.left) + Xpix;       
    obj.style.left = px;
}

function ProcessKeypress(e)
{
    var myObj = "pantul";
    var moveBy = 10;
    obj = document.getElementById(myObj);
    x=parseInt(obj.style.left);

    if (e.keyCode) keycode=e.keyCode;
    else keycode=e.which;
    ch=String.fromCharCode(keycode);

    if(x > 220 || x <720)
    {
        if(ch=='a')         moveObj(myObj, -moveBy);
        else if(ch=='d')    moveObj(myObj, moveBy);
    }
}   
4

1 回答 1

0
Character codes:

37 - left

38 - up

39 - right

40 - down

所以你可以使用键码(不是字符),

function ProcessKeypress(e)
{
    var myObj = "pantul";
    var moveBy = 10;
    obj = document.getElementById(myObj);
    x=parseInt(obj.style.left);

    if (e.keyCode) keycode=e.keyCode;
    else keycode=e.which;

    if(x > 220 || x <720)
    {
        if(keycode == 37)         moveObj(myObj, -moveBy);
        else if(keycode == 39)    moveObj(myObj, moveBy);
    }
}   
于 2012-04-15T14:26:58.327 回答