多くの人がここで同様の質問をするのを見てきましたが、どれも私にはうまくいかないようです. 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;
}
}
このコードを修正する必要があるのか 、それとももっと簡単なものがあるのか わかりません。これを行うより簡単な方法があれば、私に知らせてください。