如何让这个物体移动得更快

How to make this object move faster

在我的代码中,每次按下箭头键时,我都会让一个对象(一个人形精灵)移动 1 个像素。当你按住箭头键时,这个人会非常非常慢。我尝试在每次按下按键时增加数量,但这不够流畅。有人能告诉我如何让他每次移动一个像素但每 100 毫秒移动一个像素吗?谢谢,感谢您的帮助。

    function moveLeft() {
    var newLeft = left - 1;
    left = newLeft;
    myElement.style.left = newLeft + 'px';

}
function moveUp() {
    var newTop = topStyle - 1;
    topStyle = newTop;
    myElement.style.top = newTop + 'px';

}
function moveRight() {
    var newLeft2 = left + 1;
    left = newLeft2;
    myElement.style.left = newLeft2 + 'px';

}
function moveDown() {
    var newTop2 = topStyle + 1;
    topStyle = newTop2
    myElement.style.top = newTop2 + 'px';
}

试试吧,我只是为你重写了整个代码。现在我每 100 毫秒使用一个间隔

var myElement = document.getElementById("character");

var move_left = false;
var move_up = false;
var move_right = false;
var move_down = false;

setInterval(function (){
 if (move_left) myElement.style.left = (getIntfromStyle(myElement.style.left) - 1) + 'px';
 if (move_up) myElement.style.top = (getIntfromStyle(myElement.style.top) - 1) + 'px';
 if (move_right) myElement.style.left = (getIntfromStyle(myElement.style.left) + 1) + 'px';
 if (move_down) myElement.style.top = (getIntfromStyle(myElement.style.top) + 1) + 'px';
}, 100);

// with this function, you dont need topStyle & left variables to store previous positions
// you can get current positioin easilysily
function getIntfromStyle(in_style) {
 return parseInt(in_style.replace('px', ''));
}

// i use keyboard to tell code when character should be moved and when must stop
document.onkeydown = function(e) {
    e = e || window.event;
    switch(e.which || e.keyCode) {
  case 37: // left
   move_left = true;
   break;
        case 38: // up
   move_up = true;
   break;
        case 39: // right
   move_right = true;
   break;
        case 40: // down
   move_down = true;
   break;
        default: return; // exit this handler for other keys
 }
 e.preventDefault(); // prevent the default action (scroll / move caret)
}

document.onkeyup = function(e) {
    e = e || window.event;
    switch(e.which || e.keyCode) {
  case 37: // left
   move_left = false;
   break;
        case 38: // up
   move_up = false;
   break;
        case 39: // right
   move_right = false;
   break;
        case 40: // down
   move_down = false;
   break;
 }
}
<div id="character"  style="background:red;width:20px;height:20px;position:fixed;display:block;left:0;top:0"></div>