JavaScript使用箭头键移动图像

时间:2013-04-10 01:19:29

标签: javascript html jquery-animate key move

我看到很多人在这里提出类似的问题,但似乎没有人能为我工作。我有一个img,id为'character'。我希望它在左键单击时向左移动,在右键单击时向右移动。这是我的代码:

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;
    }
}

我不知道是否应修复此代码,或者是否有更简单的内容。如果您有更简单的方法,请告诉我。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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';
    }
}
相关问题