JavaScript move an image with arrow keys

2019-08-28 02:15发布

问题:

I've seen lots of people ask similar questions here, but none of them seem to work for me. I have an img, with the id 'character'. I want it to move left on left click and right on right click. This is the code I have:

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

I don't know if I should fix this code, or if there is something simpler. If you have a simpler way of doing this, please let me know.

回答1:

Why not use 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})
  }
});

Here is a demo of it in action



回答2:

Your steps are different in the left and right function. use one variable to avoid that. Example

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