I have a div with an id of bottom_arrow and I want to use my keyboard arrows left/right to mo开发者_如何学Pythonve the div left and right 100px. How can I do this?
As a rule keypress events go to an input or some control that has focus, if you need them generally on a page, which is a sometimes a little frowned upon due to removing standard behavior, then bind the keydown event to the whole document.
$('body').keydown(function(event) {
switch (event.keycode) {
case 37: // left arrow key
$('#bottom_arrow').animate({ 'left': '-=100' });
break;
case 39: // right arrow key
$('#bottom_arrow').animate({ 'left': '+=100' });
break;
}
});
I have used keydown, rather than keypress as a user would expect it to trigger whilst pressing the key.
$('body').keydown(function(event) {
switch (event.keycode) {
case 37: // left arrow key
$('#bottom_arrow').animate({ 'left': '-=100' });
break;
case 39: // right arrow key
$('#bottom_arrow').animate({ 'left': '+=100' });
break;
}
});
According to Jquery documentation, use event.which instead.
$('body').keydown(function(event) {
switch (event.which) {
case 37: // left arrow key
$('#bottom_arrow').animate({ 'left': '-=100' });
break;
case 39: // right arrow key
$('#bottom_arrow').animate({ 'left': '+=100' });
break;
}
});
加载中,请稍侯......
精彩评论