关于文档类的一点小发现

代码
1 package
2 {
3
4  import flash.display.Sprite;
5  import flash.events.KeyboardEvent;
6
7  public class Test extends Sprite
8 {
9
10 public function Test()
11 {
12 super();
13 this.addEventListener(KeyboardEvent.KEY_UP,showKeycode);
14 }
15 private function showKeycode(e:KeyboardEvent):void{
16 trace(e.keyCode.toString());
17 }
18 }
19 }
20
21 package
22 {
23
24 import flash.display.Sprite;
25 import flash.events.KeyboardEvent;
26
27 public class Test extends Sprite
28 {
29
30 public function Test()
31 {
32 super();
33 this.stage.addEventListener(KeyboardEvent.KEY_UP,showKeycode);
34 }
35 private function showKeycode(e:KeyboardEvent):void{
36 trace(e.keyCode.toString());
37 }
38 }
39 }
40
41

这两个类同为文档测试类,只是第一个类用自身,也就是this监听键盘按下事件,而第二个类用this.stage来监听键盘事件。编译后我们会发现他们同样生成一个空白的flash,但第一个类编译后,监听不到事件。而第二个类编译后却监听到了事件。

代码
1 package
2 {
3
4 import flash.display.Sprite;
5 import flash.events.KeyboardEvent;
6
7 public class Test extends Sprite
8 {
9
10 public function Test()
11 {
12 super();
13 this.addEventListener(KeyboardEvent.KEY_UP,showKeycode);
14
15 text=new TextField();
16 text.multiline=false;
17 text.width=200;
18 text.height=20;
19 text.x=200;
20 text.y=200;
21 text.border=true;
22 text.background=true;
23 this.addChild(text);
24 }
25 private function showKeycode(e:KeyboardEvent):void{
26 trace(e.keyCode.toString());
27 }
28 }
29 }
30
31

当我们把第一个类中,加入一个text,并当text被先中时,也可以监听到事件。

这里我总结了一下,文档类中,sprite本身不能监听键盘事件,只有当其自身中加入新的显示状态,并被聚焦时,才可以监听键盘事件。文档类的 this.stage可以在flash被聚焦时监听键盘事件。顺便说一句,flash的事件键盘监听,好像都是在flash被聚焦后才可以监听到。我是在webflash中测试的。air就不知道了

偶的一个在实战中未必用到的小小发现,帖出来与大家分享,贵在研究嘛,呵呵

原文地址:https://www.cnblogs.com/crkay/p/1747873.html