JQuery ~ How to keep moving the object when keydown
In JQuery ~ I hope to make a simple character moving, Stop > Left || right.
This script make #moveCharacter turn left walk 10px once.
How can I keydown keep turn left walking,when keyup stop walking (like a character)??
// Left moving
$(document).keydown(function(e){
if (e.keyCode == 37) {
$("#moveCharacter").animate({marginLeft: "-=10px"}, {queue:false});
return false;
}
});
2.I try to change keypress() but it has not work.....what wrong?
var xTriggered = 0;
$(document).keypress(function(e){
xTriggered++;
if (e.which == '37') {
$("#moveCharacter").animate({marginLeft: "-="+xTriggered+"px"开发者_StackOverflow中文版}, {queue:false});
return false;
}
});
You want to be using the keypress event instead of keydown. As per the JQuery API:
If the user presses and holds a key, a keydown event is triggered once, but separate keypress events are triggered for each inserted character
May this code will work as you want
var xTriggered = 0;
$(document).keydown(function(e){
xTriggered++;
if (e.which == '37') {
$("#moveCharacter").animate({marginLeft: "-="+xTriggered+"px"}, {queue:false});
return false;
}
//EDIT
$(document).keydown(function(e) {
if(e.keyCode == 37) { // left
$("#moveCharacter").animate({ marginLeft: "-=10"});
}
});
$(document).keyup(function(e) {
$("#moveCharacter").queue("fx", []);
$("#moveCharacter").stop(); });
精彩评论