Javascript keyup doesn't work as expected, it executes in instances where I have not removed my finger from a button

妖精的绣舞 提交于 2019-12-07 11:53:34

问题


I'm trying to create a simple game in javascript and I'm stuck on how to deal with keys.

Small example:

function keyUpEvent(event) {
    alert(event.keyCode);
}
window.addEventListener("keyup", keyUpEvent, false);

I'm running Ubuntu 9.10 and testing it in Firefox 3.5 and Chromium.

If I press and release a button instantly I get an alert, which is to be expected, but when I press and hold a button I get a small pause and then a series of alert windows, the expected result is that I only get an alert window when I remove my finger from a button.

I reason it has something to do with the fact that when I press and hold a button in a text area for example I get one character, small pause, and then a series of characters: dddddddddddddddd.

I believe it's possible to get around this or do it more right or whatever since this game for example: http://bohuco.net/testing/gamequery/pong.html seams not to be affected by this. But I notice if I try out the jquery keyup demo ( api.jquery.com/keyup/ ) I get the same problem.

How can I implement basic game key event handling?


回答1:


The example that you give, have the solution - why not follow it ?

Its use a timer after keyDown, and its not call direct the function that do the job. And this is the trick, you must use a timer.

Here is a similar problem that can give you one more idea.



来源:https://stackoverflow.com/questions/2752524/javascript-keyup-doesnt-work-as-expected-it-executes-in-instances-where-i-have

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!