如何使用键盘上的箭头键分别将div向左/向右移动100px [英] How use keyboard arrow keys to move a div 100px left/right respectively

查看:221
本文介绍了如何使用键盘上的箭头键分别将div向左/向右移动100px的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ID为bottom_arrow的div,我想使用左/右键盘箭头将div左右移动100px.我该怎么办?

I have a div with an id of bottom_arrow and I want to use my keyboard arrows left/right to move the div left and right 100px. How can I do this?

推荐答案

通常,按键事件会进入具有焦点的输入或某些控件,如果您通常需要将它们放在页面上,有时会有些皱眉由于删除了标准行为,因此将keydown事件绑定到整个文档.

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

我使用的是keydown,而不是keypress,因为用户希望它在按下键时触发.

I have used keydown, rather than keypress as a user would expect it to trigger whilst pressing the key.

这篇关于如何使用键盘上的箭头键分别将div向左/向右移动100px的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆