如何获取有关按下哪个键多长时间的信息?
想象一下这段代码:
if (navigator.appName == "Opera")
document.onkeypress = function (e) { console.log(e.keyCode); };
else
document.onkeydown = function (e) { console.log(e.keyCode); };
我想它的作用是非常明显的。问题是,如果你长时间持有密钥,它就会被注册很多次。在我的应用程序中,这是一个问题,因为它使我的应用程序执行大量不必要的计算。是否有可能以某种方式仅获得一次按键
,但包含按键持续时间的信息?
Imagine this code:
if (navigator.appName == "Opera")
document.onkeypress = function (e) { console.log(e.keyCode); };
else
document.onkeydown = function (e) { console.log(e.keyCode); };
What it does is pretty obvious, I guess. The problem is, if you hold the key for a long period of time, it will be registered a lot of times. In my app, this is a problem because it makes my app do a lot of unnecessary computing. Is it possible to somehow only get a keypress
once, but with info on how long the key was held?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这里:
现场演示: http://jsfiddle.net/EeXVX/ 1/show/
(删除 URL 的“show/”部分以查看演示代码)
因此,您拥有
pressed
对象,该对象监视当前按下的键以及按下的键他们当时在什么时间点按下。在 keyup 处理程序中,您可以确定是否按下了按键,如果是,则通过减去 keyup/keydown 事件的时间戳来计算持续时间。
Here you go:
Live demo: http://jsfiddle.net/EeXVX/1/show/
(remove the "show/" part of the URL to view the code for the demo)
So you have the
pressed
object which monitors which keys are currently being pressed and at what point (in time) they have been pressed.Inside the keyup handler, you determine if the key was being pressed, and if so, calculate the duration by subtracting the time-stamps of the keyup/keydown events.
您是否尝试过执行诸如
Have you tried doing somethign like,