区分按键和保持键 [英] Differentiate between key pressed and key held

查看:65
本文介绍了区分按键和保持键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个javascript函数,当按下向下"键时会运行.我想,如果按住'down'键,该功能将根本无法运行.

I have a javascript function which runs when the 'down' key is pressed. I would like, that if the 'down' key is held down, the function would not run at all.

我考虑过keydown和keyup之间的时间安排,如果时间少于1秒,则该功能将在keyup上运行.问题是,如果我按住该键,浏览器会将该键视为连续多次按下该键.

I thought about timing between keydown and keyup, if the time is less than 1 second then the function would run on keyup. The problem is, if I hold the key down the browser sees it as the key being pressed many times in succession.

有更好的方法吗?

谢谢

推荐答案

如果我理解您的问题是您的浏览器将一个键被解释为多个键按下事件.您希望按住键与只按一下键时会有所不同.并且您希望该差异基于您认为应该构成掌握"密钥的某个时间.因此,您需要通过跟踪按键事件来区分保持和按下.以下伪代码将解决此问题:

If I understand your problem is that your browser interprets a key being held as multiple keydown events. You want something different to happen if a key is held versus when it's simply pressed; and you want that difference to be based on some time which you think should constitute "holding" the key. So you need to differentiate between a hold and a press by tracking the keyup event. The following pseudocode will resolve this problem:

按键时:

if !yourBool 
    start timer

yourBool = true 

在Keyup上:

on Keyup:

if timer < yourTime
    do something

yourBool = false

这将起作用,因为除非发生键入事件,否则计时器不会重新启动.

This will work because the timer will not restart unless keyup event has occurred.

现在...如果您的浏览器将键保持方式解释为:
Keydown,Keyup,Keydown,Keyup .......
那么您对这种方法有疑问.

Now... if your browser interprets key holding as:
Keydown, Keyup, Keydown, Keyup.......
then you have a problem with this approach.

这篇关于区分按键和保持键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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