My JavaScript code is as follows:
我的JavaScript代码如下:
$(document).keydown(function(event){
var move, inter;
clearInterval(inter);
inter = setInterval(move = function() {
var dir = $(".snake").data('dir');
var snake = $('.snake');
var food = $('.food');
if(dir == 'top') {
snake.css({"top": $(".snake").position().top + 5 + "px"});
}
if(dir == 'bottom') {
snake.css({"top": $(".snake").position().top - 5 + "px"});
}
if(dir == 'left') {
snake.css({"left": $(".snake").position().left + 5 + "px"});
}
if(dir == 'right') {
snake.css({"left": $(".snake").position().left - 5 + "px"});
}
}, 1500);
if(event.which == 40) {
$(".snake").data('dir','top');
} else if(event.which == 39) {
$(".snake").data('dir','left');
} else if(event.which == 37) {
$(".snake").data('dir','right');
} else if(event.which == 38) {
$(".snake").data('dir','bottom');
};
});
http://jsfiddle.net/6bKHc/94/
When I hold down one of the arrows keys, the snake is starting to move faster, how can I turn that off? You can test it yourself.
当我按下其中一个箭头键时,蛇开始移动得更快,我怎么能把它关掉?你可以自己测试一下。
1 个解决方案
#1
2
Your setInterval
is called inside your eventhandler. Move setinterval
outside, along with a shared dir variable. Then you will have no need for clearinterval
.
您的setInterval在您的eventhandler中调用。将setinterval移动到外部,以及共享的dir变量。那你就不需要明确的间隔了。
var dir = 'bottom';
setInterval(move = function() {
var snake = $('.snake');
var food = $('.food');
if(dir == 'top') {
snake.css({"top": $(".snake").position().top + 5 + "px"});
}
if(dir == 'bottom') {
snake.css({"top": $(".snake").position().top - 5 + "px"});
}
if(dir == 'left') {
snake.css({"left": $(".snake").position().left + 5 + "px"});
}
if(dir == 'right') {
snake.css({"left": $(".snake").position().left - 5 + "px"});
}
}, 150);
$(document).keydown(function(event){
if(event.which == 40) {
dir = 'top';
} else if(event.which == 39) {
dir = 'left';
} else if(event.which == 37) {
dir = 'right';
} else if(event.which == 38) {
dir = 'bottom';
};
});
http://jsfiddle.net/zatsq/
#1
2
Your setInterval
is called inside your eventhandler. Move setinterval
outside, along with a shared dir variable. Then you will have no need for clearinterval
.
您的setInterval在您的eventhandler中调用。将setinterval移动到外部,以及共享的dir变量。那你就不需要明确的间隔了。
var dir = 'bottom';
setInterval(move = function() {
var snake = $('.snake');
var food = $('.food');
if(dir == 'top') {
snake.css({"top": $(".snake").position().top + 5 + "px"});
}
if(dir == 'bottom') {
snake.css({"top": $(".snake").position().top - 5 + "px"});
}
if(dir == 'left') {
snake.css({"left": $(".snake").position().left + 5 + "px"});
}
if(dir == 'right') {
snake.css({"left": $(".snake").position().left - 5 + "px"});
}
}, 150);
$(document).keydown(function(event){
if(event.which == 40) {
dir = 'top';
} else if(event.which == 39) {
dir = 'left';
} else if(event.which == 37) {
dir = 'right';
} else if(event.which == 38) {
dir = 'bottom';
};
});
http://jsfiddle.net/zatsq/