当前位置:Gxlcms > html代码 > 用仿ActionScript的语法来编写html5——第七篇,自定义按钮

用仿ActionScript的语法来编写html5——第七篇,自定义按钮

时间:2021-07-01 10:21:17 帮助过:45人阅读

第七篇,自定义按钮


这次弄个简单点的,自定义按钮。
其实,有了前面所定义的LSprite,LBitmap等类,定义按钮就很方便了。
下面是添加按钮的代码,

  1. function gameInit(event){
  2. backLayer = new LSprite();
  3. addChild(backLayer);
  4. btn01 = new LButton(new LBitmap(new LBitmapData(imglist["replay_button_up"])),new LBitmap(new LBitmapData(imglist["replay_button_over"])));
  5. btn01.x = 76;
  6. btn01.y = 50;
  7. backLayer.addChild(btn01);
  8. btn02 = new LButton(new LBitmap(new LBitmapData(imglist["quit_button_up"])),new LBitmap(new LBitmapData(imglist["quit_button_over"])));
  9. btn02.x = 76;
  10. btn02.y = 100;
  11. backLayer.addChild(btn02);
  12. btn01.addEventListener(LMouseEvent.MOUSE_DOWN, onmousedown01);
  13. btn02.addEventListener(LMouseEvent.MOUSE_DOWN, onmousedown02);
  14. }
  15. function onmousedown01(event){
  16. alert("btn01 on click");
  17. }
  18. function onmousedown02(event){
  19. alert("btn02 on click");
  20. }

原理:建立一个继承自LSprite的LButton类,给按钮设定两个图片,然后侦听鼠标位置,当鼠标移动到按钮上的时候,变换按钮状态,就是一个简单的按钮。


这里,我用mousemove来侦听鼠标位置,给LGlobal类添加一个buttonList数组,当创建按钮的时候,把按钮加入到buttonList,然后当移动鼠标的时候,就可以从buttonList数组判断鼠标是否在按钮上,然后当按钮被删除后,将按钮从buttonList数组中删除。


一些修改:
1,修改LSprite类,添加die方法,每个LSprite当被removeChild的时候,调用自己的die方法,die方法里放一些被移除是必需处理的事件,比如这次的按钮,要从buttonList中删除。
2,给每个构造器添加objectindex,用来区分每个对象。
3,修改addChild方法,添加DisplayObject.parent = self,就是给每个自对象指定父级对象。


准备完毕,开始创建按钮类LButton。

  1. function LButton(bitmap_up,bitmap_over){
  2. base(this,LSprite,[]);
  3. var self = this;
  4. self.type = "LButton";
  5. self.bitmap_up = bitmap_up;
  6. self.addChild(bitmap_up);
  7. if(bitmap_over == null){
  8. bitmap_over = bitmap_up;
  9. }else{
  10. self.addChild(bitmap_over);
  11. }
  12. self.bitmap_over = bitmap_over;
  13. self.bitmap_over.visible = false;
  14. self.bitmap_up.visible = true;
  15. LGlobal.buttonList.push(self);
  16. }
  17. LButton.prototype.buttonModeChange = function (){
  18. var self = this;
  19. var cood={x:0,y:0};
  20. var parent = self.parent;
  21. while(parent != "root"){
  22. cood.x += parent.x;
  23. cood.y += parent.y;
  24. parent = parent.parent;
  25. }
  26. if(self.ismouseon(LGlobal.mouseMoveEvent,cood)){
  27. self.bitmap_up.visible = false;
  28. self.bitmap_over.visible = true;
  29. }else{
  30. self.bitmap_over.visible = false;
  31. self.bitmap_up.visible = true;
  32. }
  33. }
  34. LButton.prototype.die = function (){
  35. var self = this;
  36. arguments.callee.super.die.call(this);
  37. for(var i=0;i<LGlobal.buttonList.length;i++){
  38. if(LGlobal.buttonList[i].objectindex == self.objectindex){
  39. LGlobal.buttonList.splice(i,1);
  40. break;
  41. }
  42. }
  43. }

以上就是用仿ActionScript的语法来编写html5——第七篇,自定义按钮的内容,更多相关内容请关注PHP中文网(www.gxlcms.com)!

人气教程排行