0

多くの人がここで同様の質問をするのを見てきましたが、どれも私にはうまくいかないようです. ID「キャラクター」のimgがあります。左クリックで左に移動し、右クリックで右に移動したい。これは私が持っているコードです:

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

このコードを修正する必要があるのか​​ 、それとももっと簡単なものがあるのか​​ わかりません。これを行うより簡単な方法があれば、私に知らせてください。

4

2 に答える 2

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

これが動作中のデモです

于 2013-04-10T01:56:16.340 に答える
0

あなたのステップは左右の機能が異なります。それを避けるために1つの変数を使用してください。例

 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';
    }
}
于 2013-04-10T01:46:08.673 に答える