在KeyboardEvent
对象中,我遇到了关键事件,有没有办法知道事件是第一次按下,还是按下按键时重复?
我想在按下键时切换设置;我可以听一下按键,但我更喜欢按下按键后立即采取动作...只要我能够在生成按键重复事件时阻止它来回切换。
答案 0 :(得分:8)
经过测试和工作
import flash.events.KeyboardEvent;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onUp);
var keys:Object = {};
function onDown(e:KeyboardEvent):void {
if( ! Boolean(e.keyCode in keys)) {
trace("First Time");
keys[e.keyCode] = true;
}
}
function onUp(e:KeyboardEvent):void {
delete keys[e.keyCode];
}
将密钥代码存储在对象中以及在密钥上使用delete的想法最初来自Senoculars库。见http://www.senocular.com/flash/actionscript/
答案 1 :(得分:3)
最简单的方法是删除或禁用KEY_DOWN
侦听器中带有标记的KEY_DOWN
侦听器,然后在KEY_UP
中添加或启用它。
答案 2 :(得分:0)
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
private function onKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.SPACE)
{
stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
}
}
private function onKeyUp(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.SPACE)
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.removeEventListener(KeyboardEvent.KEY_UP, onKeyUp);
}
}