많은 사람들이 여기에 비슷한 질문을했지만, 아무도 저에게 효과가없는 것으로 나타났습니다. 나는 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;
}
}
이 코드를 수정해야하는지 또는 더 간단한 것이 있는지는 잘 모릅니다. 이 작업을 수행하는 간단한 방법이 있다면 알려 주시기 바랍니다.
입니까? – Daedalus
잘 진행되지만 왼쪽으로 가면 30px로 점프하고 그 다음에는 100px와 같이 점프합니다. –
왼쪽 및 오른쪽 기능에서 단계가 다릅니다. 그것을 피하기 위해 하나의 변수를 사용하십시오. – bksi