如何禁用 jQuery 中的重复按键
当用户按住某个键时,我希望 keydown() 事件仅被调用一次,但它会被调用直到用户停止按下该键。
这就是我想要做的:
$(document).keydown(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '39'){
$("#box").animate({"left": "+=30px"}, "fast");
}
});
所以,当用户按下右箭头键时,我希望 div#box 向右移动 30px。它会移动,但如果用户按住按键,它就会飞走。
我需要它每次按下时仅移动 30px,然后停止,即使用户按住该键也是如此。你知道如何实现吗?
When user keeps a key pressed, I want the keydown() event get called only once, but its called until user stops pressing the key.
Here is what I am trying to do:
$(document).keydown(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '39'){
$("#box").animate({"left": "+=30px"}, "fast");
}
});
So, when user presses right arrow key, I want the div#box to move 30px to the right. It moves but if user keeps key pressed it flies away.
I need it to move only by 30px per press, and stop, even if user keeps the key pressed. Do you know how it can be accomplished?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
跟踪哪些键被按下,并忽略键码 39,直到按键将其清除:
Keep track of which keys are down, and ignore keycode 39 until a keyup even clears it:
保留一个标志并在
keydown
时将其变为绿色,但我建议keyup
keep a flag and turn it green upon
keydown
i would suggestkeyup
though