如何让这个对象更快地移动

时间:2016-11-21 22:39:25

标签: javascript html keypress

在我的代码中,每按一次箭头键,我就会使一个对象(一个man精灵)移动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';
}

1 个答案:

答案 0 :(得分:0)

尝试一下,我只是为你重写整个代码。现在我每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>