我见过很多人在这里提出类似的问题,但他们都没有为我工作。我有一个img,id为'character'。我希望它左移左键,右键右键。这是我的代码: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 2013-04-10 01:24:21
它工作正常走左边,但是当它的权利,它每一次跳跃像30像素,然后像100px的,等等,越走越远。 – 2013-04-10 01:38:10
您的步骤在左右功能上有所不同。使用一个变量来避免这种情况 – bksi 2013-04-10 01:44:53