2013-04-10 2 views
0

많은 사람들이 여기에 비슷한 질문을했지만, 아무도 저에게 효과가없는 것으로 나타났습니다. 나는 id 'character'라는 img를 가지고있다. 왼쪽 클릭으로 왼쪽으로 이동하고 오른쪽 클릭으로 오른쪽으로 이동합니다. 이것은 내가 가지고있는 코드입니다.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

+0

잘 진행되지만 왼쪽으로 가면 30px로 점프하고 그 다음에는 100px와 같이 점프합니다. –

+0

왼쪽 및 오른쪽 기능에서 단계가 다릅니다. 그것을 피하기 위해 하나의 변수를 사용하십시오. – bksi

답변

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

고마워요. 나는 그것에 대해 완전히 잊었다. –

+0

한계 검사를 구현하지 않았으므로 도움이 필요하면 알려주십시오. – lightswitch05

+0

괜찮으 시다면, 정말 좋을 것입니다. 나는 창 크기를 잘못 부르고 있다고 생각한다. if 문을 만들려고했는데, 기본적으로 # img.style.left의 값이 전체 창 너비보다 작 으면 애니메이션이 적용되지 않지만 작동하지 않습니다. 또는 더 나은 방법을 알고 있다면 좋습니다. –

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'; 
    } 
} 
관련 문제