2013-04-10 118 views
0

我见过很多人在这里提出类似的问题,但他们都没有为我工作。我有一个img,id为'character'。我希望它左移左键,右键右键。这是我的代码:JavaScript用箭头键移动图像

var bound = window.innerWidth; 
function left(id) { 
    document.getElementById(id).style.left.match(/^([0-9]+)/); 
    var current = RegExp.$1; 
    if(current <=bound){ 
     document.getElementById(id).style.left = current - 0 + 'px'; 
    } 
    else{ 
     document.getElementById(id).style.left = current - 5 + 'px'; 
    } 
} 

function right(id) { 
    document.getElementById(id).style.left.match(/^([0-9]+)/); 
    var current = RegExp.$1; 
    if(current >= (bound - 5){ 
     document.getElementById(id).style.left = current + 0 + 'px'; 
    } 
    else{ 
     document.getElementById(id).style.left = current + 1 + 'px'; 
    } 
} 

document.onkeyup = KeyCheck;  
function KeyCheck() { 

    var KeyID = event.keyCode; 
    switch(KeyID) 
    { 
    case 39: 
    right('character'); 
    break; 
    case 37: 
    left('character'); 
    break; 
    } 
} 

我不知道我是否应该修改代码,或者如果有更简单的东西。如果您有更简单的方法,请告诉我。

+0

什么是你的错误? – Daedalus 2013-04-10 01:24:21

+0

它工作正常走左边,但是当它的权利,它每一次跳跃像30像素,然后像100px的,等等,越走越远。 – 2013-04-10 01:38:10

+0

您的步骤在左右功能上有所不同。使用一个变量来避免这种情况 – bksi 2013-04-10 01:44:53

回答

2

为什么不使用jQuery?

$("body").keydown(function(e) { 
    var max = $('body').width(); 
    var min = 0; 
    var move_amt = 10; 
    var position = $("#my_image").offset(); 
    if(e.which == 37) { // left 
    var new_left = ((position.left-move_amt < min) ? min : position.left-move_amt); 
    $("#my_image").offset({ left: new_left}) 
    } 
    else if(e.which == 39) { // right 
    var new_left = ((position.left+move_amt > max) ? max : position.left+move_amt); 
    $("#my_image").offset({ left: new_left}) 
    } 
}); 

这里是一个demo of it in action

+0

谢谢。我完全忘记了这一点。 – 2013-04-10 02:13:40

+0

我没有执行边界检查,让我知道你是否需要提供帮助的。 – lightswitch05 2013-04-10 02:25:00

+0

如果你不介意的话,那将会很棒。我想我错误地调用了窗口的大小。我试图使一个if语句,在那里,基本上,如果#img.style.left的值小于整个窗口的宽度,那就不是动画,但没有奏效。或者,如果你知道更好的方法,那也是好的。 – 2013-04-10 02:30:08

0

您的步骤在左右功能上有所不同。使用一个变量来避免这种情况。示例

var step = 5; 
function left(id) { 
    document.getElementById(id).style.left.match(/^([0-9]+)/); 
    var current = RegExp.$1; 
    if(current <=bound){ 
     document.getElementById(id).style.left = current - 0 + 'px'; 
    } 
    else{ 
     document.getElementById(id).style.left = current - step + 'px'; 
    } 
} 

function right(id) { 
    document.getElementById(id).style.left.match(/^([0-9]+)/); 
    var current = RegExp.$1; 
    if(current >= (bound - 5){ 
     document.getElementById(id).style.left = current + 0 + 'px'; 
    } 
    else{ 
     document.getElementById(id).style.left = current + step + 'px'; 
    } 
}