简体   繁体   中英

JavaScript move an image with arrow keys

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM