开发者

How use keyboard arrow keys to move a div 100px left/right respectively

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;
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜