[英]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 move the div left and right 100px. 我有一个id为
bottom_arrow
的div,我想使用键盘左/右方向将div左右移动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. 我用
keydown
,而不是keypress
的用户希望它触发,同时按下键。
$('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. 根据Jquery文档,请改用event.which。
$('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;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.